summaryrefslogtreecommitdiff
path: root/channels/chan_pjsip.c
blob: 69bcc187fd2f217de1da557e98e87818d5244fc0 (plain)
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
/*
 * Asterisk -- An open source telephony toolkit.
 *
 * Copyright (C) 2013, Digium, Inc.
 *
 * Joshua Colp <jcolp@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
 *
 * \author Joshua Colp <jcolp@digium.com>
 *
 * \brief PSJIP SIP Channel Driver
 *
 * \ingroup channel_drivers
 */

/*** MODULEINFO
	<depend>pjproject</depend>
	<depend>res_pjsip</depend>
	<depend>res_pjsip_session</depend>
	<support_level>core</support_level>
 ***/

#include "asterisk.h"

#include <pjsip.h>
#include <pjsip_ua.h>
#include <pjlib.h>

#include "asterisk/lock.h"
#include "asterisk/channel.h"
#include "asterisk/module.h"
#include "asterisk/pbx.h"
#include "asterisk/rtp_engine.h"
#include "asterisk/acl.h"
#include "asterisk/callerid.h"
#include "asterisk/file.h"
#include "asterisk/cli.h"
#include "asterisk/app.h"
#include "asterisk/musiconhold.h"
#include "asterisk/causes.h"
#include "asterisk/taskprocessor.h"
#include "asterisk/dsp.h"
#include "asterisk/stasis_endpoints.h"
#include "asterisk/stasis_channels.h"
#include "asterisk/indications.h"
#include "asterisk/format_cache.h"
#include "asterisk/translate.h"
#include "asterisk/threadstorage.h"
#include "asterisk/features_config.h"
#include "asterisk/pickup.h"
#include "asterisk/test.h"

#include "asterisk/res_pjsip.h"
#include "asterisk/res_pjsip_session.h"
#include "asterisk/stream.h"

#include "pjsip/include/chan_pjsip.h"
#include "pjsip/include/dialplan_functions.h"
#include "pjsip/include/cli_functions.h"

AST_THREADSTORAGE(uniqueid_threadbuf);
#define UNIQUEID_BUFSIZE 256

static const char channel_type[] = "PJSIP";

static unsigned int chan_idx;

static void chan_pjsip_pvt_dtor(void *obj)
{
}

/* \brief Asterisk core interaction functions */
static struct ast_channel *chan_pjsip_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause);
static struct ast_channel *chan_pjsip_request_with_stream_topology(const char *type,
	struct ast_stream_topology *topology, const struct ast_assigned_ids *assignedids,
	const struct ast_channel *requestor, const char *data, int *cause);
static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text);
static int chan_pjsip_digit_begin(struct ast_channel *ast, char digit);
static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout);
static int chan_pjsip_hangup(struct ast_channel *ast);
static int chan_pjsip_answer(struct ast_channel *ast);
static struct ast_frame *chan_pjsip_read_stream(struct ast_channel *ast);
static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *f);
static int chan_pjsip_write_stream(struct ast_channel *ast, int stream_num, struct ast_frame *f);
static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
static int chan_pjsip_transfer(struct ast_channel *ast, const char *target);
static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
static int chan_pjsip_devicestate(const char *data);
static int chan_pjsip_queryoption(struct ast_channel *ast, int option, void *data, int *datalen);
static const char *chan_pjsip_get_uniqueid(struct ast_channel *ast);

/*! \brief PBX interface structure for channel registration */
struct ast_channel_tech chan_pjsip_tech = {
	.type = channel_type,
	.description = "PJSIP Channel Driver",
	.requester = chan_pjsip_request,
	.requester_with_stream_topology = chan_pjsip_request_with_stream_topology,
	.send_text = chan_pjsip_sendtext,
	.send_digit_begin = chan_pjsip_digit_begin,
	.send_digit_end = chan_pjsip_digit_end,
	.call = chan_pjsip_call,
	.hangup = chan_pjsip_hangup,
	.answer = chan_pjsip_answer,
	.read_stream = chan_pjsip_read_stream,
	.write = chan_pjsip_write,
	.write_stream = chan_pjsip_write_stream,
	.exception = chan_pjsip_read_stream,
	.indicate = chan_pjsip_indicate,
	.transfer = chan_pjsip_transfer,
	.fixup = chan_pjsip_fixup,
	.devicestate = chan_pjsip_devicestate,
	.queryoption = chan_pjsip_queryoption,
	.func_channel_read = pjsip_acf_channel_read,
	.get_pvt_uniqueid = chan_pjsip_get_uniqueid,
	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER
};

/*! \brief SIP session interaction functions */
static void chan_pjsip_session_begin(struct ast_sip_session *session);
static void chan_pjsip_session_end(struct ast_sip_session *session);
static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata);
static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata);

/*! \brief SIP session supplement structure */
static struct ast_sip_session_supplement chan_pjsip_supplement = {
	.method = "INVITE",
	.priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL,
	.session_begin = chan_pjsip_session_begin,
	.session_end = chan_pjsip_session_end,
	.incoming_request = chan_pjsip_incoming_request,
	.incoming_response = chan_pjsip_incoming_response,
	/* It is important that this supplement runs after media has been negotiated */
	.response_priority = AST_SIP_SESSION_AFTER_MEDIA,
};

static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata);

static struct ast_sip_session_supplement chan_pjsip_ack_supplement = {
	.method = "ACK",
	.priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL,
	.incoming_request = chan_pjsip_incoming_ack,
};

/*! \brief Function called by RTP engine to get local audio RTP peer */
static enum ast_rtp_glue_result chan_pjsip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
	struct ast_sip_endpoint *endpoint;
	struct ast_datastore *datastore;
	struct ast_sip_session_media *media;

	if (!channel || !channel->session) {
		return AST_RTP_GLUE_RESULT_FORBID;
	}

	/* XXX Getting the first RTP instance for direct media related stuff seems just
	 * absolutely wrong. But the native RTP bridge knows no other method than single-stream
	 * for direct media. So this is the best we can do.
	 */
	media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
	if (!media || !media->rtp) {
		return AST_RTP_GLUE_RESULT_FORBID;
	}

	datastore = ast_sip_session_get_datastore(channel->session, "t38");
	if (datastore) {
		ao2_ref(datastore, -1);
		return AST_RTP_GLUE_RESULT_FORBID;
	}

	endpoint = channel->session->endpoint;

	*instance = media->rtp;
	ao2_ref(*instance, +1);

	ast_assert(endpoint != NULL);
	if (endpoint->media.rtp.encryption != AST_SIP_MEDIA_ENCRYPT_NONE) {
		return AST_RTP_GLUE_RESULT_FORBID;
	}

	if (endpoint->media.direct_media.enabled) {
		return AST_RTP_GLUE_RESULT_REMOTE;
	}

	return AST_RTP_GLUE_RESULT_LOCAL;
}

/*! \brief Function called by RTP engine to get local video RTP peer */
static enum ast_rtp_glue_result chan_pjsip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
	struct ast_sip_endpoint *endpoint;
	struct ast_sip_session_media *media;

	if (!channel || !channel->session) {
		return AST_RTP_GLUE_RESULT_FORBID;
	}

	media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO];
	if (!media || !media->rtp) {
		return AST_RTP_GLUE_RESULT_FORBID;
	}

	endpoint = channel->session->endpoint;

	*instance = media->rtp;
	ao2_ref(*instance, +1);

	ast_assert(endpoint != NULL);
	if (endpoint->media.rtp.encryption != AST_SIP_MEDIA_ENCRYPT_NONE) {
		return AST_RTP_GLUE_RESULT_FORBID;
	}

	return AST_RTP_GLUE_RESULT_LOCAL;
}

/*! \brief Function called by RTP engine to get peer capabilities */
static void chan_pjsip_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
{
	ast_format_cap_append_from_cap(result, ast_channel_nativeformats(chan), AST_MEDIA_TYPE_UNKNOWN);
}

/*! \brief Destructor function for \ref transport_info_data */
static void transport_info_destroy(void *obj)
{
	struct transport_info_data *data = obj;
	ast_free(data);
}

/*! \brief Datastore used to store local/remote addresses for the
 * INVITE request that created the PJSIP channel */
static struct ast_datastore_info transport_info = {
	.type = "chan_pjsip_transport_info",
	.destroy = transport_info_destroy,
};

static struct ast_datastore_info direct_media_mitigation_info = { };

static int direct_media_mitigate_glare(struct ast_sip_session *session)
{
	RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);

	if (session->endpoint->media.direct_media.glare_mitigation ==
			AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
		return 0;
	}

	datastore = ast_sip_session_get_datastore(session, "direct_media_glare_mitigation");
	if (!datastore) {
		return 0;
	}

	/* Removing the datastore ensures we won't try to mitigate glare on subsequent reinvites */
	ast_sip_session_remove_datastore(session, "direct_media_glare_mitigation");

	if ((session->endpoint->media.direct_media.glare_mitigation ==
			AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_OUTGOING &&
			session->inv_session->role == PJSIP_ROLE_UAC) ||
			(session->endpoint->media.direct_media.glare_mitigation ==
			AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_INCOMING &&
			session->inv_session->role == PJSIP_ROLE_UAS)) {
		return 1;
	}

	return 0;
}

/*! \brief Helper function to find the position for RTCP */
static int rtp_find_rtcp_fd_position(struct ast_sip_session *session, struct ast_rtp_instance *rtp)
{
	int index;

	for (index = 0; index < AST_VECTOR_SIZE(&session->active_media_state->read_callbacks); ++index) {
		struct ast_sip_session_media_read_callback_state *callback_state =
			AST_VECTOR_GET_ADDR(&session->active_media_state->read_callbacks, index);

		if (callback_state->fd != ast_rtp_instance_fd(rtp, 1)) {
			continue;
		}

		return index;
	}

	return -1;
}

/*!
 * \pre chan is locked
 */
static int check_for_rtp_changes(struct ast_channel *chan, struct ast_rtp_instance *rtp,
		struct ast_sip_session_media *media, struct ast_sip_session *session)
{
	int changed = 0, position = -1;

	if (media->rtp) {
		position = rtp_find_rtcp_fd_position(session, media->rtp);
	}

	if (rtp) {
		changed = ast_rtp_instance_get_and_cmp_remote_address(rtp, &media->direct_media_addr);
		if (media->rtp) {
			if (position != -1) {
				ast_channel_set_fd(chan, position + AST_EXTENDED_FDS, -1);
			}
			ast_rtp_instance_set_prop(media->rtp, AST_RTP_PROPERTY_RTCP, 0);
		}
	} else if (!ast_sockaddr_isnull(&media->direct_media_addr)){
		ast_sockaddr_setnull(&media->direct_media_addr);
		changed = 1;
		if (media->rtp) {
			ast_rtp_instance_set_prop(media->rtp, AST_RTP_PROPERTY_RTCP, 1);
			if (position != -1) {
				ast_channel_set_fd(chan, position + AST_EXTENDED_FDS, ast_rtp_instance_fd(media->rtp, 1));
			}
		}
	}

	return changed;
}

struct rtp_direct_media_data {
	struct ast_channel *chan;
	struct ast_rtp_instance *rtp;
	struct ast_rtp_instance *vrtp;
	struct ast_format_cap *cap;
	struct ast_sip_session *session;
};

static void rtp_direct_media_data_destroy(void *data)
{
	struct rtp_direct_media_data *cdata = data;

	ao2_cleanup(cdata->session);
	ao2_cleanup(cdata->cap);
	ao2_cleanup(cdata->vrtp);
	ao2_cleanup(cdata->rtp);
	ao2_cleanup(cdata->chan);
}

static struct rtp_direct_media_data *rtp_direct_media_data_create(
	struct ast_channel *chan, struct ast_rtp_instance *rtp, struct ast_rtp_instance *vrtp,
	const struct ast_format_cap *cap, struct ast_sip_session *session)
{
	struct rtp_direct_media_data *cdata = ao2_alloc(sizeof(*cdata), rtp_direct_media_data_destroy);

	if (!cdata) {
		return NULL;
	}

	cdata->chan = ao2_bump(chan);
	cdata->rtp = ao2_bump(rtp);
	cdata->vrtp = ao2_bump(vrtp);
	cdata->cap = ao2_bump((struct ast_format_cap *)cap);
	cdata->session = ao2_bump(session);

	return cdata;
}

static int send_direct_media_request(void *data)
{
	struct rtp_direct_media_data *cdata = data;
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(cdata->chan);
	struct ast_sip_session *session;
	int changed = 0;
	int res = 0;

	/* XXX In an ideal world each media stream would be direct, but for now preserve behavior
	 * and connect only the default media sessions for audio and video.
	 */

	/* The channel needs to be locked when checking for RTP changes.
	 * Otherwise, we could end up destroying an underlying RTCP structure
	 * at the same time that the channel thread is attempting to read RTCP
	 */
	ast_channel_lock(cdata->chan);
	session = channel->session;
	if (session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO]) {
		changed |= check_for_rtp_changes(
			cdata->chan, cdata->rtp, session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO], session);
	}
	if (session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO]) {
		changed |= check_for_rtp_changes(
			cdata->chan, cdata->vrtp, session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO], session);
	}
	ast_channel_unlock(cdata->chan);

	if (direct_media_mitigate_glare(cdata->session)) {
		ast_debug(4, "Disregarding setting RTP on %s: mitigating re-INVITE glare\n", ast_channel_name(cdata->chan));
		ao2_ref(cdata, -1);
		return 0;
	}

	if (cdata->cap && ast_format_cap_count(cdata->cap) &&
	    !ast_format_cap_identical(cdata->session->direct_media_cap, cdata->cap)) {
		ast_format_cap_remove_by_type(cdata->session->direct_media_cap, AST_MEDIA_TYPE_UNKNOWN);
		ast_format_cap_append_from_cap(cdata->session->direct_media_cap, cdata->cap, AST_MEDIA_TYPE_UNKNOWN);
		changed = 1;
	}

	if (changed) {
		ast_debug(4, "RTP changed on %s; initiating direct media update\n", ast_channel_name(cdata->chan));
		res = ast_sip_session_refresh(cdata->session, NULL, NULL, NULL,
			cdata->session->endpoint->media.direct_media.method, 1, NULL);
	}

	ao2_ref(cdata, -1);
	return res;
}

/*! \brief Function called by RTP engine to change where the remote party should send media */
static int chan_pjsip_set_rtp_peer(struct ast_channel *chan,
		struct ast_rtp_instance *rtp,
		struct ast_rtp_instance *vrtp,
		struct ast_rtp_instance *tpeer,
		const struct ast_format_cap *cap,
		int nat_active)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
	struct ast_sip_session *session = channel->session;
	struct rtp_direct_media_data *cdata;

	/* Don't try to do any direct media shenanigans on early bridges */
	if ((rtp || vrtp || tpeer) && !ast_channel_is_bridged(chan)) {
		ast_debug(4, "Disregarding setting RTP on %s: channel is not bridged\n", ast_channel_name(chan));
		return 0;
	}

	if (nat_active && session->endpoint->media.direct_media.disable_on_nat) {
		ast_debug(4, "Disregarding setting RTP on %s: NAT is active\n", ast_channel_name(chan));
		return 0;
	}

	cdata = rtp_direct_media_data_create(chan, rtp, vrtp, cap, session);
	if (!cdata) {
		return 0;
	}

	if (ast_sip_push_task(session->serializer, send_direct_media_request, cdata)) {
		ast_log(LOG_ERROR, "Unable to send direct media request for channel %s\n", ast_channel_name(chan));
		ao2_ref(cdata, -1);
	}

	return 0;
}

/*! \brief Local glue for interacting with the RTP engine core */
static struct ast_rtp_glue chan_pjsip_rtp_glue = {
	.type = "PJSIP",
	.get_rtp_info = chan_pjsip_get_rtp_peer,
	.get_vrtp_info = chan_pjsip_get_vrtp_peer,
	.get_codec = chan_pjsip_get_codec,
	.update_peer = chan_pjsip_set_rtp_peer,
};

static void set_channel_on_rtp_instance(const struct ast_sip_session *session,
	const char *channel_id)
{
	int i;

	for (i = 0; i < AST_VECTOR_SIZE(&session->active_media_state->sessions); ++i) {
		struct ast_sip_session_media *session_media;

		session_media = AST_VECTOR_GET(&session->active_media_state->sessions, i);
		if (!session_media || !session_media->rtp) {
			continue;
		}

		ast_rtp_instance_set_channel_id(session_media->rtp, channel_id);
	}
}

/*!
 * \brief Determine if a topology is compatible with format capabilities
 *
 * This will return true if ANY formats in the topology are compatible with the format
 * capabilities.
 *
 * XXX When supporting true multistream, we will need to be sure to mark which streams from
 * top1 are compatible with which streams from top2. Then the ones that are not compatible
 * will need to be marked as "removed" so that they are negotiated as expected.
 *
 * \param top Topology
 * \param cap Format capabilities
 * \retval 1 The topology has at least one compatible format
 * \retval 0 The topology has no compatible formats or an error occurred.
 */
static int compatible_formats_exist(struct ast_stream_topology *top, struct ast_format_cap *cap)
{
	struct ast_format_cap *cap_from_top;
	int res;

	cap_from_top = ast_format_cap_from_stream_topology(top);

	if (!cap_from_top) {
		return 0;
	}

	res = ast_format_cap_iscompatible(cap_from_top, cap);
	ao2_ref(cap_from_top, -1);

	return res;
}

/*! \brief Function called to create a new PJSIP Asterisk channel */
static struct ast_channel *chan_pjsip_new(struct ast_sip_session *session, int state, const char *exten, const char *title, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *cid_name)
{
	struct ast_channel *chan;
	struct ast_format_cap *caps;
	RAII_VAR(struct chan_pjsip_pvt *, pvt, NULL, ao2_cleanup);
	struct ast_sip_channel_pvt *channel;
	struct ast_variable *var;
	struct ast_stream_topology *topology;

	if (!(pvt = ao2_alloc_options(sizeof(*pvt), chan_pjsip_pvt_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK))) {
		return NULL;
	}

	chan = ast_channel_alloc_with_endpoint(1, state,
		S_COR(session->id.number.valid, session->id.number.str, ""),
		S_COR(session->id.name.valid, session->id.name.str, ""),
		session->endpoint->accountcode,
		exten, session->endpoint->context,
		assignedids, requestor, 0,
		session->endpoint->persistent, "PJSIP/%s-%08x",
		ast_sorcery_object_get_id(session->endpoint),
		(unsigned) ast_atomic_fetchadd_int((int *) &chan_idx, +1));
	if (!chan) {
		return NULL;
	}

	ast_channel_tech_set(chan, &chan_pjsip_tech);

	if (!(channel = ast_sip_channel_pvt_alloc(pvt, session))) {
		ast_channel_unlock(chan);
		ast_hangup(chan);
		return NULL;
	}

	ast_channel_tech_pvt_set(chan, channel);

	if (!ast_stream_topology_get_count(session->pending_media_state->topology) ||
		!compatible_formats_exist(session->pending_media_state->topology, session->endpoint->media.codecs)) {
		caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
		if (!caps) {
			ast_channel_unlock(chan);
			ast_hangup(chan);
			return NULL;
		}
		ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
		topology = ast_stream_topology_clone(session->endpoint->media.topology);
	} else {
		caps = ast_format_cap_from_stream_topology(session->pending_media_state->topology);
		topology = ast_stream_topology_clone(session->pending_media_state->topology);
	}

	if (!topology || !caps) {
		ao2_cleanup(caps);
		ast_stream_topology_free(topology);
		ast_channel_unlock(chan);
		ast_hangup(chan);
		return NULL;
	}

	ast_channel_stage_snapshot(chan);

	ast_channel_nativeformats_set(chan, caps);
	ast_channel_set_stream_topology(chan, topology);

	if (!ast_format_cap_empty(caps)) {
		struct ast_format *fmt;

		fmt = ast_format_cap_get_best_by_type(caps, AST_MEDIA_TYPE_AUDIO);
		if (!fmt) {
			/* Since our capabilities aren't empty, this will succeed */
			fmt = ast_format_cap_get_format(caps, 0);
		}
		ast_channel_set_writeformat(chan, fmt);
		ast_channel_set_rawwriteformat(chan, fmt);
		ast_channel_set_readformat(chan, fmt);
		ast_channel_set_rawreadformat(chan, fmt);
		ao2_ref(fmt, -1);
	}

	ao2_ref(caps, -1);

	if (state == AST_STATE_RING) {
		ast_channel_rings_set(chan, 1);
	}

	ast_channel_adsicpe_set(chan, AST_ADSI_UNAVAILABLE);

	ast_party_id_copy(&ast_channel_caller(chan)->id, &session->id);
	ast_party_id_copy(&ast_channel_caller(chan)->ani, &session->id);

	if (!ast_strlen_zero(exten)) {
		/* Set provided DNID on the new channel. */
		ast_channel_dialed(chan)->number.str = ast_strdup(exten);
	}

	ast_channel_priority_set(chan, 1);

	ast_channel_callgroup_set(chan, session->endpoint->pickup.callgroup);
	ast_channel_pickupgroup_set(chan, session->endpoint->pickup.pickupgroup);

	ast_channel_named_callgroups_set(chan, session->endpoint->pickup.named_callgroups);
	ast_channel_named_pickupgroups_set(chan, session->endpoint->pickup.named_pickupgroups);

	if (!ast_strlen_zero(session->endpoint->language)) {
		ast_channel_language_set(chan, session->endpoint->language);
	}

	if (!ast_strlen_zero(session->endpoint->zone)) {
		struct ast_tone_zone *zone = ast_get_indication_zone(session->endpoint->zone);
		if (!zone) {
			ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", session->endpoint->zone);
		}
		ast_channel_zone_set(chan, zone);
	}

	for (var = session->endpoint->channel_vars; var; var = var->next) {
		char buf[512];
		pbx_builtin_setvar_helper(chan, var->name, ast_get_encoded_str(
						  var->value, buf, sizeof(buf)));
	}

	ast_channel_stage_snapshot_done(chan);
	ast_channel_unlock(chan);

	set_channel_on_rtp_instance(session, ast_channel_uniqueid(chan));

	return chan;
}

static int answer(void *data)
{
	pj_status_t status = PJ_SUCCESS;
	pjsip_tx_data *packet = NULL;
	struct ast_sip_session *session = data;

	if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
		ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
			session->inv_session->cause,
			pjsip_get_status_text(session->inv_session->cause)->ptr);
#ifdef HAVE_PJSIP_INV_SESSION_REF
		pjsip_inv_dec_ref(session->inv_session);
#endif
		return 0;
	}

	pjsip_dlg_inc_lock(session->inv_session->dlg);
	if (session->inv_session->invite_tsx) {
		status = pjsip_inv_answer(session->inv_session, 200, NULL, NULL, &packet);
	} else {
		ast_log(LOG_ERROR,"Cannot answer '%s' because there is no associated SIP transaction\n",
			ast_channel_name(session->channel));
	}
	pjsip_dlg_dec_lock(session->inv_session->dlg);

	if (status == PJ_SUCCESS && packet) {
		ast_sip_session_send_response(session, packet);
	}

#ifdef HAVE_PJSIP_INV_SESSION_REF
	pjsip_inv_dec_ref(session->inv_session);
#endif

	if (status != PJ_SUCCESS) {
		char err[PJ_ERR_MSG_SIZE];

		pj_strerror(status, err, sizeof(err));
		ast_log(LOG_WARNING,"Cannot answer '%s': %s\n",
			ast_channel_name(session->channel), err);
		/*
		 * Return this value so we can distinguish between this
		 * failure and the threadpool synchronous push failing.
		 */
		return -2;
	}
	return 0;
}

/*! \brief Function called by core when we should answer a PJSIP session */
static int chan_pjsip_answer(struct ast_channel *ast)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
	struct ast_sip_session *session;
	int res;

	if (ast_channel_state(ast) == AST_STATE_UP) {
		return 0;
	}

	ast_setstate(ast, AST_STATE_UP);
	session = ao2_bump(channel->session);

#ifdef HAVE_PJSIP_INV_SESSION_REF
	if (pjsip_inv_add_ref(session->inv_session) != PJ_SUCCESS) {
		ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
		ao2_ref(session, -1);
		return -1;
	}
#endif

	/* the answer task needs to be pushed synchronously otherwise a race condition
	   can occur between this thread and bridging (specifically when native bridging
	   attempts to do direct media) */
	ast_channel_unlock(ast);
	res = ast_sip_push_task_synchronous(session->serializer, answer, session);
	if (res) {
		if (res == -1) {
			ast_log(LOG_ERROR,"Cannot answer '%s': Unable to push answer task to the threadpool.\n",
				ast_channel_name(session->channel));
#ifdef HAVE_PJSIP_INV_SESSION_REF
			pjsip_inv_dec_ref(session->inv_session);
#endif
		}
		ao2_ref(session, -1);
		ast_channel_lock(ast);
		return -1;
	}
	ao2_ref(session, -1);
	ast_channel_lock(ast);

	return 0;
}

/*! \brief Internal helper function called when CNG tone is detected */
static struct ast_frame *chan_pjsip_cng_tone_detected(struct ast_sip_session *session, struct ast_frame *f)
{
	const char *target_context;
	int exists;
	int dsp_features;

	dsp_features = ast_dsp_get_features(session->dsp);
	dsp_features &= ~DSP_FEATURE_FAX_DETECT;
	if (dsp_features) {
		ast_dsp_set_features(session->dsp, dsp_features);
	} else {
		ast_dsp_free(session->dsp);
		session->dsp = NULL;
	}

	/* If already executing in the fax extension don't do anything */
	if (!strcmp(ast_channel_exten(session->channel), "fax")) {
		return f;
	}

	target_context = S_OR(ast_channel_macrocontext(session->channel), ast_channel_context(session->channel));

	/*
	 * We need to unlock the channel here because ast_exists_extension has the
	 * potential to start and stop an autoservice on the channel. Such action
	 * is prone to deadlock if the channel is locked.
	 *
	 * ast_async_goto() has its own restriction on not holding the channel lock.
	 */
	ast_channel_unlock(session->channel);
	ast_frfree(f);
	f = &ast_null_frame;
	exists = ast_exists_extension(session->channel, target_context, "fax", 1,
		S_COR(ast_channel_caller(session->channel)->id.number.valid,
			ast_channel_caller(session->channel)->id.number.str, NULL));
	if (exists) {
		ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n",
			ast_channel_name(session->channel));
		pbx_builtin_setvar_helper(session->channel, "FAXEXTEN", ast_channel_exten(session->channel));
		if (ast_async_goto(session->channel, target_context, "fax", 1)) {
			ast_log(LOG_ERROR, "Failed to async goto '%s' into fax extension in '%s'\n",
				ast_channel_name(session->channel), target_context);
		}
	} else {
		ast_log(LOG_NOTICE, "FAX CNG detected on '%s' but no fax extension in '%s'\n",
			ast_channel_name(session->channel), target_context);
	}
	ast_channel_lock(session->channel);

	return f;
}

/*!
 * \brief Function called by core to read any waiting frames 
 *
 * \note The channel is already locked.
 */
static struct ast_frame *chan_pjsip_read_stream(struct ast_channel *ast)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
	struct ast_sip_session *session = channel->session;
	struct ast_sip_session_media_read_callback_state *callback_state;
	struct ast_frame *f;
	int fdno = ast_channel_fdno(ast) - AST_EXTENDED_FDS;

	if (fdno >= AST_VECTOR_SIZE(&session->active_media_state->read_callbacks)) {
		return &ast_null_frame;
	}

	callback_state = AST_VECTOR_GET_ADDR(&session->active_media_state->read_callbacks, fdno);
	f = callback_state->read_callback(session, callback_state->session);

	if (!f) {
		return f;
	}

	if (f->frametype != AST_FRAME_VOICE ||
		callback_state->session != session->active_media_state->default_session[callback_state->session->type]) {
		return f;
	}

	session = channel->session;

	/*
	 * Asymmetric RTP only has one native format set at a time.
	 * Therefore we need to update the native format to the current
	 * raw read format BEFORE the native format check
	 */
	if (!session->endpoint->asymmetric_rtp_codec &&
		ast_format_cmp(ast_channel_rawwriteformat(ast), f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
		struct ast_format_cap *caps;

		/* For maximum compatibility we ensure that the formats match that of the received media */
		ast_debug(1, "Oooh, got a frame with format of %s on channel '%s' when we're sending '%s', switching to match\n",
			ast_format_get_name(f->subclass.format), ast_channel_name(ast),
			ast_format_get_name(ast_channel_rawwriteformat(ast)));

		caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
		if (caps) {
			ast_format_cap_append_from_cap(caps, ast_channel_nativeformats(ast), AST_MEDIA_TYPE_UNKNOWN);
			ast_format_cap_remove_by_type(caps, AST_MEDIA_TYPE_AUDIO);
			ast_format_cap_append(caps, f->subclass.format, 0);
			ast_channel_nativeformats_set(ast, caps);
			ao2_ref(caps, -1);
		}

		ast_set_write_format_path(ast, ast_channel_writeformat(ast), f->subclass.format);
		ast_set_read_format_path(ast, ast_channel_readformat(ast), f->subclass.format);

		if (ast_channel_is_bridged(ast)) {
			ast_channel_set_unbridged_nolock(ast, 1);
		}
	}

	if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
		ast_debug(1, "Oooh, got a frame with format of %s on channel '%s' when it has not been negotiated\n",
			ast_format_get_name(f->subclass.format), ast_channel_name(ast));

		ast_frfree(f);
		return &ast_null_frame;
	}

	if (session->dsp) {
		int dsp_features;

		dsp_features = ast_dsp_get_features(session->dsp);
		if ((dsp_features & DSP_FEATURE_FAX_DETECT)
			&& session->endpoint->faxdetect_timeout
			&& session->endpoint->faxdetect_timeout <= ast_channel_get_up_time(ast)) {
			dsp_features &= ~DSP_FEATURE_FAX_DETECT;
			if (dsp_features) {
				ast_dsp_set_features(session->dsp, dsp_features);
			} else {
				ast_dsp_free(session->dsp);
				session->dsp = NULL;
			}
			ast_debug(3, "Channel driver fax CNG detection timeout on %s\n",
				ast_channel_name(ast));
		}
	}
	if (session->dsp) {
		f = ast_dsp_process(ast, session->dsp, f);
		if (f && (f->frametype == AST_FRAME_DTMF)) {
			if (f->subclass.integer == 'f') {
				ast_debug(3, "Channel driver fax CNG detected on %s\n",
					ast_channel_name(ast));
				f = chan_pjsip_cng_tone_detected(session, f);
			} else {
				ast_debug(3, "* Detected inband DTMF '%c' on '%s'\n", f->subclass.integer,
					ast_channel_name(ast));
			}
		}
	}

	return f;
}

static int chan_pjsip_write_stream(struct ast_channel *ast, int stream_num, struct ast_frame *frame)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
	struct ast_sip_session *session = channel->session;
	struct ast_sip_session_media *media = NULL;
	int res = 0;

	/* The core provides a guarantee that the stream will exist when we are called if stream_num is provided */
	if (stream_num >= 0) {
		/* What is not guaranteed is that a media session will exist */
		if (stream_num < AST_VECTOR_SIZE(&channel->session->active_media_state->sessions)) {
			media = AST_VECTOR_GET(&channel->session->active_media_state->sessions, stream_num);
		}
	}

	switch (frame->frametype) {
	case AST_FRAME_VOICE:
		if (!media) {
			return 0;
		} else if (media->type != AST_MEDIA_TYPE_AUDIO) {
			ast_debug(3, "Channel %s stream %d is of type '%s', not audio!\n",
				ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
			return 0;
		} else if (media == channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO] &&
			ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), frame->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
			struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
			struct ast_str *write_transpath = ast_str_alloca(256);
			struct ast_str *read_transpath = ast_str_alloca(256);

			ast_log(LOG_WARNING,
				"Channel %s asked to send %s frame when native formats are %s (rd:%s->%s;%s wr:%s->%s;%s)\n",
				ast_channel_name(ast),
				ast_format_get_name(frame->subclass.format),
				ast_format_cap_get_names(ast_channel_nativeformats(ast), &cap_buf),
				ast_format_get_name(ast_channel_rawreadformat(ast)),
				ast_format_get_name(ast_channel_readformat(ast)),
				ast_translate_path_to_str(ast_channel_readtrans(ast), &read_transpath),
				ast_format_get_name(ast_channel_writeformat(ast)),
				ast_format_get_name(ast_channel_rawwriteformat(ast)),
				ast_translate_path_to_str(ast_channel_writetrans(ast), &write_transpath));
			return 0;
		} else if (media->write_callback) {
			res = media->write_callback(session, media, frame);

		}
		break;
	case AST_FRAME_VIDEO:
		if (!media) {
			return 0;
		} else if (media->type != AST_MEDIA_TYPE_VIDEO) {
			ast_debug(3, "Channel %s stream %d is of type '%s', not video!\n",
				ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
			return 0;
		} else if (media->write_callback) {
			res = media->write_callback(session, media, frame);
		}
		break;
	case AST_FRAME_MODEM:
		if (!media) {
			return 0;
		} else if (media->type != AST_MEDIA_TYPE_IMAGE) {
			ast_debug(3, "Channel %s stream %d is of type '%s', not image!\n",
				ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
			return 0;
		} else if (media->write_callback) {
			res = media->write_callback(session, media, frame);
		}
		break;
	case AST_FRAME_CNG:
		break;
	default:
		ast_log(LOG_WARNING, "Can't send %u type frames with PJSIP\n", frame->frametype);
		break;
	}

	return res;
}

static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *frame)
{
	return chan_pjsip_write_stream(ast, -1, frame);
}

/*! \brief Function called by core to change the underlying owner channel */
static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(newchan);

	if (channel->session->channel != oldchan) {
		return -1;
	}

	/*
	 * The masquerade has suspended the channel's session
	 * serializer so we can safely change it outside of
	 * the serializer thread.
	 */
	channel->session->channel = newchan;

	set_channel_on_rtp_instance(channel->session, ast_channel_uniqueid(newchan));

	return 0;
}

/*! AO2 hash function for on hold UIDs */
static int uid_hold_hash_fn(const void *obj, const int flags)
{
	const char *key = obj;

	switch (flags & OBJ_SEARCH_MASK) {
	case OBJ_SEARCH_KEY:
		break;
	case OBJ_SEARCH_OBJECT:
		break;
	default:
		/* Hash can only work on something with a full key. */
		ast_assert(0);
		return 0;
	}
	return ast_str_hash(key);
}

/*! AO2 sort function for on hold UIDs */
static int uid_hold_sort_fn(const void *obj_left, const void *obj_right, const int flags)
{
	const char *left = obj_left;
	const char *right = obj_right;
	int cmp;

	switch (flags & OBJ_SEARCH_MASK) {
	case OBJ_SEARCH_OBJECT:
	case OBJ_SEARCH_KEY:
		cmp = strcmp(left, right);
		break;
	case OBJ_SEARCH_PARTIAL_KEY:
		cmp = strncmp(left, right, strlen(right));
		break;
	default:
		/* Sort can only work on something with a full or partial key. */
		ast_assert(0);
		cmp = 0;
		break;
	}
	return cmp;
}

static struct ao2_container *pjsip_uids_onhold;

/*!
 * \brief Add a channel ID to the list of PJSIP channels on hold
 *
 * \param chan_uid - Unique ID of the channel being put into the hold list
 *
 * \retval 0 Channel has been added to or was already in the hold list
 * \retval -1 Failed to add channel to the hold list
 */
static int chan_pjsip_add_hold(const char *chan_uid)
{
	RAII_VAR(char *, hold_uid, NULL, ao2_cleanup);

	hold_uid = ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY);
	if (hold_uid) {
		/* Device is already on hold. Nothing to do. */
		return 0;
	}

	/* Device wasn't in hold list already. Create a new one. */
	hold_uid = ao2_alloc_options(strlen(chan_uid) + 1, NULL,
		AO2_ALLOC_OPT_LOCK_NOLOCK);
	if (!hold_uid) {
		return -1;
	}

	ast_copy_string(hold_uid, chan_uid, strlen(chan_uid) + 1);

	if (ao2_link(pjsip_uids_onhold, hold_uid) == 0) {
		return -1;
	}

	return 0;
}

/*!
 * \brief Remove a channel ID from the list of PJSIP channels on hold
 *
 * \param chan_uid - Unique ID of the channel being taken out of the hold list
 */
static void chan_pjsip_remove_hold(const char *chan_uid)
{
	ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY | OBJ_UNLINK | OBJ_NODATA);
}

/*!
 * \brief Determine whether a channel ID is in the list of PJSIP channels on hold
 *
 * \param chan_uid - Channel being checked
 *
 * \retval 0 The channel is not in the hold list
 * \retval 1 The channel is in the hold list
 */
static int chan_pjsip_get_hold(const char *chan_uid)
{
	RAII_VAR(char *, hold_uid, NULL, ao2_cleanup);

	hold_uid = ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY);
	if (!hold_uid) {
		return 0;
	}

	return 1;
}

/*! \brief Function called to get the device state of an endpoint */
static int chan_pjsip_devicestate(const char *data)
{
	RAII_VAR(struct ast_sip_endpoint *, endpoint, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", data), ao2_cleanup);
	enum ast_device_state state = AST_DEVICE_UNKNOWN;
	RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, NULL, ao2_cleanup);
	RAII_VAR(struct stasis_cache *, cache, NULL, ao2_cleanup);
	struct ast_devstate_aggregate aggregate;
	int num, inuse = 0;

	if (!endpoint) {
		return AST_DEVICE_INVALID;
	}

	endpoint_snapshot = ast_endpoint_latest_snapshot(ast_endpoint_get_tech(endpoint->persistent),
		ast_endpoint_get_resource(endpoint->persistent));

	if (!endpoint_snapshot) {
		return AST_DEVICE_INVALID;
	}

	if (endpoint_snapshot->state == AST_ENDPOINT_OFFLINE) {
		state = AST_DEVICE_UNAVAILABLE;
	} else if (endpoint_snapshot->state == AST_ENDPOINT_ONLINE) {
		state = AST_DEVICE_NOT_INUSE;
	}

	if (!endpoint_snapshot->num_channels || !(cache = ast_channel_cache())) {
		return state;
	}

	ast_devstate_aggregate_init(&aggregate);

	ao2_ref(cache, +1);

	for (num = 0; num < endpoint_snapshot->num_channels; num++) {
		RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
		struct ast_channel_snapshot *snapshot;

		msg = stasis_cache_get(cache, ast_channel_snapshot_type(),
			endpoint_snapshot->channel_ids[num]);

		if (!msg) {
			continue;
		}

		snapshot = stasis_message_data(msg);

		if (chan_pjsip_get_hold(snapshot->uniqueid)) {
			ast_devstate_aggregate_add(&aggregate, AST_DEVICE_ONHOLD);
		} else {
			ast_devstate_aggregate_add(&aggregate, ast_state_chan2dev(snapshot->state));
		}

		if ((snapshot->state == AST_STATE_UP) || (snapshot->state == AST_STATE_RING) ||
			(snapshot->state == AST_STATE_BUSY)) {
			inuse++;
		}
	}

	if (endpoint->devicestate_busy_at && (inuse == endpoint->devicestate_busy_at)) {
		state = AST_DEVICE_BUSY;
	} else if (ast_devstate_aggregate_result(&aggregate) != AST_DEVICE_INVALID) {
		state = ast_devstate_aggregate_result(&aggregate);
	}

	return state;
}

/*! \brief Function called to query options on a channel */
static int chan_pjsip_queryoption(struct ast_channel *ast, int option, void *data, int *datalen)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
	struct ast_sip_session *session = channel->session;
	int res = -1;
	enum ast_t38_state state = T38_STATE_UNAVAILABLE;

	switch (option) {
	case AST_OPTION_T38_STATE:
		if (session->endpoint->media.t38.enabled) {
			switch (session->t38state) {
			case T38_LOCAL_REINVITE:
			case T38_PEER_REINVITE:
				state = T38_STATE_NEGOTIATING;
				break;
			case T38_ENABLED:
				state = T38_STATE_NEGOTIATED;
				break;
			case T38_REJECTED:
				state = T38_STATE_REJECTED;
				break;
			default:
				state = T38_STATE_UNKNOWN;
				break;
			}
		}

		*((enum ast_t38_state *) data) = state;
		res = 0;

		break;
	default:
		break;
	}

	return res;
}

static const char *chan_pjsip_get_uniqueid(struct ast_channel *ast)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
	char *uniqueid = ast_threadstorage_get(&uniqueid_threadbuf, UNIQUEID_BUFSIZE);

	if (!uniqueid) {
		return "";
	}

	ast_copy_pj_str(uniqueid, &channel->session->inv_session->dlg->call_id->id, UNIQUEID_BUFSIZE);

	return uniqueid;
}

struct indicate_data {
	struct ast_sip_session *session;
	int condition;
	int response_code;
	void *frame_data;
	size_t datalen;
};

static void indicate_data_destroy(void *obj)
{
	struct indicate_data *ind_data = obj;

	ast_free(ind_data->frame_data);
	ao2_ref(ind_data->session, -1);
}

static struct indicate_data *indicate_data_alloc(struct ast_sip_session *session,
		int condition, int response_code, const void *frame_data, size_t datalen)
{
	struct indicate_data *ind_data = ao2_alloc(sizeof(*ind_data), indicate_data_destroy);

	if (!ind_data) {
		return NULL;
	}

	ind_data->frame_data = ast_malloc(datalen);
	if (!ind_data->frame_data) {
		ao2_ref(ind_data, -1);
		return NULL;
	}

	memcpy(ind_data->frame_data, frame_data, datalen);
	ind_data->datalen = datalen;
	ind_data->condition = condition;
	ind_data->response_code = response_code;
	ao2_ref(session, +1);
	ind_data->session = session;

	return ind_data;
}

static int indicate(void *data)
{
	pjsip_tx_data *packet = NULL;
	struct indicate_data *ind_data = data;
	struct ast_sip_session *session = ind_data->session;
	int response_code = ind_data->response_code;

	if ((session->inv_session->state != PJSIP_INV_STATE_DISCONNECTED) &&
		(pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS)) {
		ast_sip_session_send_response(session, packet);
	}

#ifdef HAVE_PJSIP_INV_SESSION_REF
	pjsip_inv_dec_ref(session->inv_session);
#endif
	ao2_ref(ind_data, -1);

	return 0;
}

/*! \brief Send SIP INFO with video update request */
static int transmit_info_with_vidupdate(void *data)
{
	const char * xml =
		"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
		" <media_control>\r\n"
		"  <vc_primitive>\r\n"
		"   <to_encoder>\r\n"
		"    <picture_fast_update/>\r\n"
		"   </to_encoder>\r\n"
		"  </vc_primitive>\r\n"
		" </media_control>\r\n";

	const struct ast_sip_body body = {
		.type = "application",
		.subtype = "media_control+xml",
		.body_text = xml
	};

	RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
	struct pjsip_tx_data *tdata;

	if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
		ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
			session->inv_session->cause,
			pjsip_get_status_text(session->inv_session->cause)->ptr);
		goto failure;
	}

	if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
		ast_log(LOG_ERROR, "Could not create text video update INFO request\n");
		goto failure;
	}
	if (ast_sip_add_body(tdata, &body)) {
		ast_log(LOG_ERROR, "Could not add body to text video update INFO request\n");
		goto failure;
	}
	ast_sip_session_send_request(session, tdata);

#ifdef HAVE_PJSIP_INV_SESSION_REF
	pjsip_inv_dec_ref(session->inv_session);
#endif

	return 0;

failure:
#ifdef HAVE_PJSIP_INV_SESSION_REF
	pjsip_inv_dec_ref(session->inv_session);
#endif
	return -1;

}

/*!
 * \internal
 * \brief TRUE if a COLP update can be sent to the peer.
 * \since 13.3.0
 *
 * \param session The session to see if the COLP update is allowed.
 *
 * \retval 0 Update is not allowed.
 * \retval 1 Update is allowed.
 */
static int is_colp_update_allowed(struct ast_sip_session *session)
{
	struct ast_party_id connected_id;
	int update_allowed = 0;

	if (!session->endpoint->id.send_pai && !session->endpoint->id.send_rpid) {
		return 0;
	}

	/*
	 * Check if privacy allows the update.  Check while the channel
	 * is locked so we can work with the shallow connected_id copy.
	 */
	ast_channel_lock(session->channel);
	connected_id = ast_channel_connected_effective_id(session->channel);
	if (connected_id.number.valid
		&& (session->endpoint->id.trust_outbound
			|| (ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED)) {
		update_allowed = 1;
	}
	ast_channel_unlock(session->channel);

	return update_allowed;
}

/*! \brief Update connected line information */
static int update_connected_line_information(void *data)
{
	struct ast_sip_session *session = data;

	if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
		ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
			session->inv_session->cause,
			pjsip_get_status_text(session->inv_session->cause)->ptr);
#ifdef HAVE_PJSIP_INV_SESSION_REF
		pjsip_inv_dec_ref(session->inv_session);
#endif
		ao2_ref(session, -1);
		return -1;
	}

	if (ast_channel_state(session->channel) == AST_STATE_UP
		|| session->inv_session->role == PJSIP_ROLE_UAC) {
		if (is_colp_update_allowed(session)) {
			enum ast_sip_session_refresh_method method;
			int generate_new_sdp;

			method = session->endpoint->id.refresh_method;
			if (session->inv_session->options & PJSIP_INV_SUPPORT_UPDATE) {
				method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
			}

			/* Only the INVITE method actually needs SDP, UPDATE can do without */
			generate_new_sdp = (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE);

			ast_sip_session_refresh(session, NULL, NULL, NULL, method, generate_new_sdp, NULL);
		}
	} else if (session->endpoint->id.rpid_immediate
		&& session->inv_session->state != PJSIP_INV_STATE_DISCONNECTED
		&& is_colp_update_allowed(session)) {
		int response_code = 0;

		if (ast_channel_state(session->channel) == AST_STATE_RING) {
			response_code = !session->endpoint->inband_progress ? 180 : 183;
		} else if (ast_channel_state(session->channel) == AST_STATE_RINGING) {
			response_code = 183;
		}

		if (response_code) {
			struct pjsip_tx_data *packet = NULL;

			if (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS) {
				ast_sip_session_send_response(session, packet);
			}
		}
	}

#ifdef HAVE_PJSIP_INV_SESSION_REF
	pjsip_inv_dec_ref(session->inv_session);
#endif

	ao2_ref(session, -1);
	return 0;
}

/*! \brief Callback which changes the value of locally held on the media stream */
static void local_hold_set_state(struct ast_sip_session_media *session_media, unsigned int held)
{
	if (session_media) {
		session_media->locally_held = held;
	}
}

/*! \brief Update local hold state and send a re-INVITE with the new SDP */
static int remote_send_hold_refresh(struct ast_sip_session *session, unsigned int held)
{
	AST_VECTOR_CALLBACK_VOID(&session->active_media_state->sessions, local_hold_set_state, held);
	ast_sip_session_refresh(session, NULL, NULL, NULL, AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1, NULL);
	ao2_ref(session, -1);

	return 0;
}

/*! \brief Update local hold state to be held */
static int remote_send_hold(void *data)
{
	return remote_send_hold_refresh(data, 1);
}

/*! \brief Update local hold state to be unheld */
static int remote_send_unhold(void *data)
{
	return remote_send_hold_refresh(data, 0);
}

struct topology_change_refresh_data {
	struct ast_sip_session *session;
	struct ast_sip_session_media_state *media_state;
};

static void topology_change_refresh_data_free(struct topology_change_refresh_data *refresh_data)
{
	ao2_cleanup(refresh_data->session);

	ast_sip_session_media_state_free(refresh_data->media_state);
	ast_free(refresh_data);
}

static struct topology_change_refresh_data *topology_change_refresh_data_alloc(
	struct ast_sip_session *session, const struct ast_stream_topology *topology)
{
	struct topology_change_refresh_data *refresh_data;

	refresh_data = ast_calloc(1, sizeof(*refresh_data));
	if (!refresh_data) {
		return NULL;
	}

	refresh_data->session = ao2_bump(session);
	refresh_data->media_state = ast_sip_session_media_state_alloc();
	if (!refresh_data->media_state) {
		topology_change_refresh_data_free(refresh_data);
		return NULL;
	}
	refresh_data->media_state->topology = ast_stream_topology_clone(topology);
	if (!refresh_data->media_state->topology) {
		topology_change_refresh_data_free(refresh_data);
		return NULL;
	}

	return refresh_data;
}

static int on_topology_change_response(struct ast_sip_session *session, pjsip_rx_data *rdata)
{
	if (PJSIP_IS_STATUS_IN_CLASS(rdata->msg_info.msg->line.status.code, 200)) {
		/* The topology was changed to something new so give notice to what requested
		 * it so it queries the channel and updates accordingly.
		 */
		if (session->channel) {
			ast_queue_control(session->channel, AST_CONTROL_STREAM_TOPOLOGY_CHANGED);
		}
	} else if (300 <= rdata->msg_info.msg->line.status.code) {
		/* The topology change failed, so drop the current pending media state */
		ast_sip_session_media_state_reset(session->pending_media_state);
	}

	return 0;
}

static int send_topology_change_refresh(void *data)
{
	struct topology_change_refresh_data *refresh_data = data;
	int ret;

	ret = ast_sip_session_refresh(refresh_data->session, NULL, NULL, on_topology_change_response,
		AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1, refresh_data->media_state);
	refresh_data->media_state = NULL;
	topology_change_refresh_data_free(refresh_data);

	return ret;
}

static int handle_topology_request_change(struct ast_sip_session *session,
	const struct ast_stream_topology *proposed)
{
	struct topology_change_refresh_data *refresh_data;
	int res;

	refresh_data = topology_change_refresh_data_alloc(session, proposed);
	if (!refresh_data) {
		return -1;
	}

	res = ast_sip_push_task(session->serializer, send_topology_change_refresh, refresh_data);
	if (res) {
		topology_change_refresh_data_free(refresh_data);
	}
	return res;
}

/*! \brief Function called by core to ask the channel to indicate some sort of condition */
static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
	struct ast_sip_session_media *media;
	int response_code = 0;
	int res = 0;
	char *device_buf;
	size_t device_buf_size;
	int i;
	const struct ast_stream_topology *topology;

	switch (condition) {
	case AST_CONTROL_RINGING:
		if (ast_channel_state(ast) == AST_STATE_RING) {
			if (channel->session->endpoint->inband_progress) {
				response_code = 183;
				res = -1;
			} else {
				response_code = 180;
			}
		} else {
			res = -1;
		}
		ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
		break;
	case AST_CONTROL_BUSY:
		if (ast_channel_state(ast) != AST_STATE_UP) {
			response_code = 486;
		} else {
			res = -1;
		}
		break;
	case AST_CONTROL_CONGESTION:
		if (ast_channel_state(ast) != AST_STATE_UP) {
			response_code = 503;
		} else {
			res = -1;
		}
		break;
	case AST_CONTROL_INCOMPLETE:
		if (ast_channel_state(ast) != AST_STATE_UP) {
			response_code = 484;
		} else {
			res = -1;
		}
		break;
	case AST_CONTROL_PROCEEDING:
		if (ast_channel_state(ast) != AST_STATE_UP) {
			response_code = 100;
		} else {
			res = -1;
		}
		break;
	case AST_CONTROL_PROGRESS:
		if (ast_channel_state(ast) != AST_STATE_UP) {
			response_code = 183;
		} else {
			res = -1;
		}
		ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
		break;
	case AST_CONTROL_VIDUPDATE:
		for (i = 0; i < AST_VECTOR_SIZE(&channel->session->active_media_state->sessions); ++i) {
			media = AST_VECTOR_GET(&channel->session->active_media_state->sessions, i);
			if (!media || media->type != AST_MEDIA_TYPE_VIDEO) {
				continue;
			}
			if (media->rtp) {
				/* FIXME: Only use this for VP8. Additional work would have to be done to
				 * fully support other video codecs */

				if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp8) != AST_FORMAT_CMP_NOT_EQUAL ||
					ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp9) != AST_FORMAT_CMP_NOT_EQUAL ||
					(channel->session->endpoint->media.webrtc &&
					 ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_h264) != AST_FORMAT_CMP_NOT_EQUAL)) {
					/* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
					 * RTP engine would provide a way to externally write/schedule RTCP
					 * packets */
					struct ast_frame fr;
					fr.frametype = AST_FRAME_CONTROL;
					fr.subclass.integer = AST_CONTROL_VIDUPDATE;
					res = ast_rtp_instance_write(media->rtp, &fr);
				} else {
					ao2_ref(channel->session, +1);
#ifdef HAVE_PJSIP_INV_SESSION_REF
					if (pjsip_inv_add_ref(channel->session->inv_session) != PJ_SUCCESS) {
						ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
						ao2_cleanup(channel->session);
					} else {
#endif
						if (ast_sip_push_task(channel->session->serializer, transmit_info_with_vidupdate, channel->session)) {
							ao2_cleanup(channel->session);
						}
#ifdef HAVE_PJSIP_INV_SESSION_REF
					}
#endif
				}
				ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Success");
			} else {
				ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Failure");
				res = -1;
			}
		}
		/* XXX If there were no video streams, then this should set
		 * res to -1
		 */
		break;
	case AST_CONTROL_CONNECTED_LINE:
		ao2_ref(channel->session, +1);
#ifdef HAVE_PJSIP_INV_SESSION_REF
		if (pjsip_inv_add_ref(channel->session->inv_session) != PJ_SUCCESS) {
			ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
			ao2_cleanup(channel->session);
			return -1;
		}
#endif
		if (ast_sip_push_task(channel->session->serializer, update_connected_line_information, channel->session)) {
#ifdef HAVE_PJSIP_INV_SESSION_REF
			pjsip_inv_dec_ref(channel->session->inv_session);
#endif
			ao2_cleanup(channel->session);
		}
		break;
	case AST_CONTROL_UPDATE_RTP_PEER:
		break;
	case AST_CONTROL_PVT_CAUSE_CODE:
		res = -1;
		break;
	case AST_CONTROL_MASQUERADE_NOTIFY:
		ast_assert(datalen == sizeof(int));
		if (*(int *) data) {
			/*
			 * Masquerade is beginning:
			 * Wait for session serializer to get suspended.
			 */
			ast_channel_unlock(ast);
			ast_sip_session_suspend(channel->session);
			ast_channel_lock(ast);
		} else {
			/*
			 * Masquerade is complete:
			 * Unsuspend the session serializer.
			 */
			ast_sip_session_unsuspend(channel->session);
		}
		break;
	case AST_CONTROL_HOLD:
		chan_pjsip_add_hold(ast_channel_uniqueid(ast));
		device_buf_size = strlen(ast_channel_name(ast)) + 1;
		device_buf = alloca(device_buf_size);
		ast_channel_get_device_name(ast, device_buf, device_buf_size);
		ast_devstate_changed_literal(AST_DEVICE_ONHOLD, 1, device_buf);
		if (!channel->session->endpoint->moh_passthrough) {
			ast_moh_start(ast, data, NULL);
		} else {
			if (ast_sip_push_task(channel->session->serializer, remote_send_hold, ao2_bump(channel->session))) {
				ast_log(LOG_WARNING, "Could not queue task to remotely put session '%s' on hold with endpoint '%s'\n",
					ast_sorcery_object_get_id(channel->session), ast_sorcery_object_get_id(channel->session->endpoint));
				ao2_ref(channel->session, -1);
			}
		}
		break;
	case AST_CONTROL_UNHOLD:
		chan_pjsip_remove_hold(ast_channel_uniqueid(ast));
		device_buf_size = strlen(ast_channel_name(ast)) + 1;
		device_buf = alloca(device_buf_size);
		ast_channel_get_device_name(ast, device_buf, device_buf_size);
		ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, 1, device_buf);
		if (!channel->session->endpoint->moh_passthrough) {
			ast_moh_stop(ast);
		} else {
			if (ast_sip_push_task(channel->session->serializer, remote_send_unhold, ao2_bump(channel->session))) {
				ast_log(LOG_WARNING, "Could not queue task to remotely take session '%s' off hold with endpoint '%s'\n",
					ast_sorcery_object_get_id(channel->session), ast_sorcery_object_get_id(channel->session->endpoint));
				ao2_ref(channel->session, -1);
			}
		}
		break;
	case AST_CONTROL_SRCUPDATE:
		break;
	case AST_CONTROL_SRCCHANGE:
		break;
	case AST_CONTROL_REDIRECTING:
		if (ast_channel_state(ast) != AST_STATE_UP) {
			response_code = 181;
		} else {
			res = -1;
		}
		break;
	case AST_CONTROL_T38_PARAMETERS:
		res = 0;

		if (channel->session->t38state == T38_PEER_REINVITE) {
			const struct ast_control_t38_parameters *parameters = data;

			if (parameters->request_response == AST_T38_REQUEST_PARMS) {
				res = AST_T38_REQUEST_PARMS;
			}
		}

		break;
	case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
		topology = data;
		res = handle_topology_request_change(channel->session, topology);
		break;
	case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
		break;
	case AST_CONTROL_STREAM_TOPOLOGY_SOURCE_CHANGED:
		break;
	case -1:
		res = -1;
		break;
	default:
		ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
		res = -1;
		break;
	}

	if (response_code) {
		struct indicate_data *ind_data = indicate_data_alloc(channel->session, condition, response_code, data, datalen);

		if (!ind_data) {
			return -1;
		}
#ifdef HAVE_PJSIP_INV_SESSION_REF
		if (pjsip_inv_add_ref(ind_data->session->inv_session) != PJ_SUCCESS) {
			ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
			ao2_cleanup(ind_data);
			return -1;
		}
#endif
		if (ast_sip_push_task(channel->session->serializer, indicate, ind_data)) {
			ast_log(LOG_NOTICE, "Cannot send response code %d to endpoint %s. Could not queue task properly\n",
					response_code, ast_sorcery_object_get_id(channel->session->endpoint));
#ifdef HAVE_PJSIP_INV_SESSION_REF
			pjsip_inv_dec_ref(ind_data->session->inv_session);
#endif
			ao2_cleanup(ind_data);
			res = -1;
		}
	}

	return res;
}

struct transfer_data {
	struct ast_sip_session *session;
	char *target;
};

static void transfer_data_destroy(void *obj)
{
	struct transfer_data *trnf_data = obj;

	ast_free(trnf_data->target);
	ao2_cleanup(trnf_data->session);
}

static struct transfer_data *transfer_data_alloc(struct ast_sip_session *session, const char *target)
{
	struct transfer_data *trnf_data = ao2_alloc(sizeof(*trnf_data), transfer_data_destroy);

	if (!trnf_data) {
		return NULL;
	}

	if (!(trnf_data->target = ast_strdup(target))) {
		ao2_ref(trnf_data, -1);
		return NULL;
	}

	ao2_ref(session, +1);
	trnf_data->session = session;

	return trnf_data;
}

static void transfer_redirect(struct ast_sip_session *session, const char *target)
{
	pjsip_tx_data *packet;
	enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
	pjsip_contact_hdr *contact;
	pj_str_t tmp;

	if (pjsip_inv_end_session(session->inv_session, 302, NULL, &packet) != PJ_SUCCESS
		|| !packet) {
		ast_log(LOG_WARNING, "Failed to redirect PJSIP session for channel %s\n",
			ast_channel_name(session->channel));
		message = AST_TRANSFER_FAILED;
		ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));

		return;
	}

	if (!(contact = pjsip_msg_find_hdr(packet->msg, PJSIP_H_CONTACT, NULL))) {
		contact = pjsip_contact_hdr_create(packet->pool);
	}

	pj_strdup2_with_null(packet->pool, &tmp, target);
	if (!(contact->uri = pjsip_parse_uri(packet->pool, tmp.ptr, tmp.slen, PJSIP_PARSE_URI_AS_NAMEADDR))) {
		ast_log(LOG_WARNING, "Failed to parse destination URI '%s' for channel %s\n",
			target, ast_channel_name(session->channel));
		message = AST_TRANSFER_FAILED;
		ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
		pjsip_tx_data_dec_ref(packet);

		return;
	}
	pjsip_msg_add_hdr(packet->msg, (pjsip_hdr *) contact);

	ast_sip_session_send_response(session, packet);
	ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
}

static void transfer_refer(struct ast_sip_session *session, const char *target)
{
	pjsip_evsub *sub;
	enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
	pj_str_t tmp;
	pjsip_tx_data *packet;
	const char *ref_by_val;
	char local_info[pj_strlen(&session->inv_session->dlg->local.info_str) + 1];

	if (pjsip_xfer_create_uac(session->inv_session->dlg, NULL, &sub) != PJ_SUCCESS) {
		message = AST_TRANSFER_FAILED;
		ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));

		return;
	}

	if (pjsip_xfer_initiate(sub, pj_cstr(&tmp, target), &packet) != PJ_SUCCESS) {
		message = AST_TRANSFER_FAILED;
		ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
		pjsip_evsub_terminate(sub, PJ_FALSE);

		return;
	}

	ref_by_val = pbx_builtin_getvar_helper(session->channel, "SIPREFERREDBYHDR");
	if (!ast_strlen_zero(ref_by_val)) {
		ast_sip_add_header(packet, "Referred-By", ref_by_val);
	} else {
		ast_copy_pj_str(local_info, &session->inv_session->dlg->local.info_str, sizeof(local_info));
		ast_sip_add_header(packet, "Referred-By", local_info);
	}

	pjsip_xfer_send_request(sub, packet);
	ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
}

static int transfer(void *data)
{
	struct transfer_data *trnf_data = data;
	struct ast_sip_endpoint *endpoint = NULL;
	struct ast_sip_contact *contact = NULL;
	const char *target = trnf_data->target;

	if (trnf_data->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
		ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
			trnf_data->session->inv_session->cause,
			pjsip_get_status_text(trnf_data->session->inv_session->cause)->ptr);
	} else {
		/* See if we have an endpoint; if so, use its contact */
		endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", target);
		if (endpoint) {
			contact = ast_sip_location_retrieve_contact_from_aor_list(endpoint->aors);
			if (contact && !ast_strlen_zero(contact->uri)) {
				target = contact->uri;
			}
		}

		if (ast_channel_state(trnf_data->session->channel) == AST_STATE_RING) {
			transfer_redirect(trnf_data->session, target);
		} else {
			transfer_refer(trnf_data->session, target);
		}
	}

#ifdef HAVE_PJSIP_INV_SESSION_REF
	pjsip_inv_dec_ref(trnf_data->session->inv_session);
#endif

	ao2_ref(trnf_data, -1);
	ao2_cleanup(endpoint);
	ao2_cleanup(contact);
	return 0;
}

/*! \brief Function called by core for Asterisk initiated transfer */
static int chan_pjsip_transfer(struct ast_channel *chan, const char *target)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
	struct transfer_data *trnf_data = transfer_data_alloc(channel->session, target);

	if (!trnf_data) {
		return -1;
	}

#ifdef HAVE_PJSIP_INV_SESSION_REF
	if (pjsip_inv_add_ref(trnf_data->session->inv_session) != PJ_SUCCESS) {
		ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
		ao2_cleanup(trnf_data);
		return -1;
	}
#endif

	if (ast_sip_push_task(channel->session->serializer, transfer, trnf_data)) {
		ast_log(LOG_WARNING, "Error requesting transfer\n");
#ifdef HAVE_PJSIP_INV_SESSION_REF
		pjsip_inv_dec_ref(trnf_data->session->inv_session);
#endif
		ao2_cleanup(trnf_data);
		return -1;
	}

	return 0;
}

/*! \brief Function called by core to start a DTMF digit */
static int chan_pjsip_digit_begin(struct ast_channel *chan, char digit)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
	struct ast_sip_session_media *media;
	int res = 0;

	media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];

	switch (channel->session->dtmf) {
	case AST_SIP_DTMF_RFC_4733:
		if (!media || !media->rtp) {
			return -1;
		}

		ast_rtp_instance_dtmf_begin(media->rtp, digit);
		break;
	case AST_SIP_DTMF_AUTO:
		if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND)) {
			return -1;
		}

		ast_rtp_instance_dtmf_begin(media->rtp, digit);
		break;
	case AST_SIP_DTMF_AUTO_INFO:
		if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_NONE)) {
			return -1;
		}
		ast_rtp_instance_dtmf_begin(media->rtp, digit);
		break;
	case AST_SIP_DTMF_NONE:
		break;
	case AST_SIP_DTMF_INBAND:
		res = -1;
		break;
	default:
		break;
	}

	return res;
}

struct info_dtmf_data {
	struct ast_sip_session *session;
	char digit;
	unsigned int duration;
};

static void info_dtmf_data_destroy(void *obj)
{
	struct info_dtmf_data *dtmf_data = obj;
	ao2_ref(dtmf_data->session, -1);
}

static struct info_dtmf_data *info_dtmf_data_alloc(struct ast_sip_session *session, char digit, unsigned int duration)
{
	struct info_dtmf_data *dtmf_data = ao2_alloc(sizeof(*dtmf_data), info_dtmf_data_destroy);
	if (!dtmf_data) {
		return NULL;
	}
	ao2_ref(session, +1);
	dtmf_data->session = session;
	dtmf_data->digit = digit;
	dtmf_data->duration = duration;
	return dtmf_data;
}

static int transmit_info_dtmf(void *data)
{
	RAII_VAR(struct info_dtmf_data *, dtmf_data, data, ao2_cleanup);

	struct ast_sip_session *session = dtmf_data->session;
	struct pjsip_tx_data *tdata;

	RAII_VAR(struct ast_str *, body_text, NULL, ast_free_ptr);

	struct ast_sip_body body = {
		.type = "application",
		.subtype = "dtmf-relay",
	};

	if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
		ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
			session->inv_session->cause,
			pjsip_get_status_text(session->inv_session->cause)->ptr);
		goto failure;
	}

	if (!(body_text = ast_str_create(32))) {
		ast_log(LOG_ERROR, "Could not allocate buffer for INFO DTMF.\n");
		goto failure;
	}
	ast_str_set(&body_text, 0, "Signal=%c\r\nDuration=%u\r\n", dtmf_data->digit, dtmf_data->duration);

	body.body_text = ast_str_buffer(body_text);

	if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
		ast_log(LOG_ERROR, "Could not create DTMF INFO request\n");
		goto failure;
	}
	if (ast_sip_add_body(tdata, &body)) {
		ast_log(LOG_ERROR, "Could not add body to DTMF INFO request\n");
		pjsip_tx_data_dec_ref(tdata);
		goto failure;
	}
	ast_sip_session_send_request(session, tdata);

#ifdef HAVE_PJSIP_INV_SESSION_REF
	pjsip_inv_dec_ref(session->inv_session);
#endif

	return 0;

failure:
#ifdef HAVE_PJSIP_INV_SESSION_REF
	pjsip_inv_dec_ref(session->inv_session);
#endif
	return -1;

}

/*! \brief Function called by core to stop a DTMF digit */
static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
	struct ast_sip_session_media *media;
	int res = 0;

	media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];

	switch (channel->session->dtmf) {
	case AST_SIP_DTMF_AUTO_INFO:
	{
		if (!media || !media->rtp) {
			return -1;
		}
		if (ast_rtp_instance_dtmf_mode_get(media->rtp) != AST_RTP_DTMF_MODE_NONE) {
			ast_debug(3, "Told to send end of digit on Auto-Info channel %s RFC4733 negotiated so using it.\n", ast_channel_name(ast));
			ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
			break;
		}
		/* If RFC_4733 was not negotiated, fail through to the DTMF_INFO processing */
		ast_debug(3, "Told to send end of digit on Auto-Info channel %s RFC4733 NOT negotiated using INFO instead.\n", ast_channel_name(ast));
	}

	case AST_SIP_DTMF_INFO:
	{
		struct info_dtmf_data *dtmf_data = info_dtmf_data_alloc(channel->session, digit, duration);

		if (!dtmf_data) {
			return -1;
		}

#ifdef HAVE_PJSIP_INV_SESSION_REF
		if (pjsip_inv_add_ref(dtmf_data->session->inv_session) != PJ_SUCCESS) {
			ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
			ao2_cleanup(dtmf_data);
			return -1;
		}
#endif

		if (ast_sip_push_task(channel->session->serializer, transmit_info_dtmf, dtmf_data)) {
			ast_log(LOG_WARNING, "Error sending DTMF via INFO.\n");
#ifdef HAVE_PJSIP_INV_SESSION_REF
			pjsip_inv_dec_ref(dtmf_data->session->inv_session);
#endif
			ao2_cleanup(dtmf_data);
			return -1;
		}
		break;
	}
	case AST_SIP_DTMF_RFC_4733:
		if (!media || !media->rtp) {
			return -1;
		}

		ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
		break;
	case AST_SIP_DTMF_AUTO:
		if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND)) {
			 return -1;
		}

		ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
		break;


	case AST_SIP_DTMF_NONE:
		break;
	case AST_SIP_DTMF_INBAND:
		res = -1;
		break;
	}

	return res;
}

static void update_initial_connected_line(struct ast_sip_session *session)
{
	struct ast_party_connected_line connected;

	/*
	 * Use the channel CALLERID() as the initial connected line data.
	 * The core or a predial handler may have supplied missing values
	 * from the session->endpoint->id.self about who we are calling.
	 */
	ast_channel_lock(session->channel);
	ast_party_id_copy(&session->id, &ast_channel_caller(session->channel)->id);
	ast_channel_unlock(session->channel);

	/* Supply initial connected line information if available. */
	if (!session->id.number.valid && !session->id.name.valid) {
		return;
	}

	ast_party_connected_line_init(&connected);
	connected.id = session->id;
	connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;

	ast_channel_queue_connected_line_update(session->channel, &connected, NULL);
}

static int call(void *data)
{
	struct ast_sip_channel_pvt *channel = data;
	struct ast_sip_session *session = channel->session;
	pjsip_tx_data *tdata;

	int res = ast_sip_session_create_invite(session, &tdata);

	if (res) {
		ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
		ast_queue_hangup(session->channel);
	} else {
		set_channel_on_rtp_instance(session, ast_channel_uniqueid(session->channel));
		update_initial_connected_line(session);
		ast_sip_session_send_request(session, tdata);
	}
	ao2_ref(channel, -1);
	return res;
}

/*! \brief Function called by core to actually start calling a remote party */
static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);

	ao2_ref(channel, +1);
	if (ast_sip_push_task(channel->session->serializer, call, channel)) {
		ast_log(LOG_WARNING, "Error attempting to place outbound call to '%s'\n", dest);
		ao2_cleanup(channel);
		return -1;
	}

	return 0;
}

/*! \brief Internal function which translates from Asterisk cause codes to SIP response codes */
static int hangup_cause2sip(int cause)
{
	switch (cause) {
	case AST_CAUSE_UNALLOCATED:             /* 1 */
	case AST_CAUSE_NO_ROUTE_DESTINATION:    /* 3 IAX2: Can't find extension in context */
	case AST_CAUSE_NO_ROUTE_TRANSIT_NET:    /* 2 */
		return 404;
	case AST_CAUSE_CONGESTION:              /* 34 */
	case AST_CAUSE_SWITCH_CONGESTION:       /* 42 */
		return 503;
	case AST_CAUSE_NO_USER_RESPONSE:        /* 18 */
		return 408;
	case AST_CAUSE_NO_ANSWER:               /* 19 */
	case AST_CAUSE_UNREGISTERED:        /* 20 */
		return 480;
	case AST_CAUSE_CALL_REJECTED:           /* 21 */
		return 403;
	case AST_CAUSE_NUMBER_CHANGED:          /* 22 */
		return 410;
	case AST_CAUSE_NORMAL_UNSPECIFIED:      /* 31 */
		return 480;
	case AST_CAUSE_INVALID_NUMBER_FORMAT:
		return 484;
	case AST_CAUSE_USER_BUSY:
		return 486;
	case AST_CAUSE_FAILURE:
		return 500;
	case AST_CAUSE_FACILITY_REJECTED:       /* 29 */
		return 501;
	case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
		return 503;
	case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
		return 502;
	case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:       /* Can't find codec to connect to host */
		return 488;
	case AST_CAUSE_INTERWORKING:    /* Unspecified Interworking issues */
		return 500;
	case AST_CAUSE_NOTDEFINED:
	default:
		ast_debug(1, "AST hangup cause %d (no match found in PJSIP)\n", cause);
		return 0;
	}

	/* Never reached */
	return 0;
}

struct hangup_data {
	int cause;
	struct ast_channel *chan;
};

static void hangup_data_destroy(void *obj)
{
	struct hangup_data *h_data = obj;

	h_data->chan = ast_channel_unref(h_data->chan);
}

static struct hangup_data *hangup_data_alloc(int cause, struct ast_channel *chan)
{
	struct hangup_data *h_data = ao2_alloc(sizeof(*h_data), hangup_data_destroy);

	if (!h_data) {
		return NULL;
	}

	h_data->cause = cause;
	h_data->chan = ast_channel_ref(chan);

	return h_data;
}

/*! \brief Clear a channel from a session along with its PVT */
static void clear_session_and_channel(struct ast_sip_session *session, struct ast_channel *ast)
{
	session->channel = NULL;
	set_channel_on_rtp_instance(session, "");
	ast_channel_tech_pvt_set(ast, NULL);
}

static int hangup(void *data)
{
	struct hangup_data *h_data = data;
	struct ast_channel *ast = h_data->chan;
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
	struct ast_sip_session *session = channel->session;
	int cause = h_data->cause;

	/*
	 * It's possible that session_terminate might cause the session to be destroyed
	 * immediately so we need to keep a reference to it so we can NULL session->channel
	 * afterwards.
	 */
	ast_sip_session_terminate(ao2_bump(session), cause);
	clear_session_and_channel(session, ast);
	ao2_cleanup(session);
	ao2_cleanup(channel);
	ao2_cleanup(h_data);
	return 0;
}

/*! \brief Function called by core to hang up a PJSIP session */
static int chan_pjsip_hangup(struct ast_channel *ast)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
	int cause;
	struct hangup_data *h_data;

	if (!channel || !channel->session) {
		return -1;
	}

	cause = hangup_cause2sip(ast_channel_hangupcause(channel->session->channel));
	h_data = hangup_data_alloc(cause, ast);

	if (!h_data) {
		goto failure;
	}

	if (ast_sip_push_task(channel->session->serializer, hangup, h_data)) {
		ast_log(LOG_WARNING, "Unable to push hangup task to the threadpool. Expect bad things\n");
		goto failure;
	}

	return 0;

failure:
	/* Go ahead and do our cleanup of the session and channel even if we're not going
	 * to be able to send our SIP request/response
	 */
	clear_session_and_channel(channel->session, ast);
	ao2_cleanup(channel);
	ao2_cleanup(h_data);

	return -1;
}

struct request_data {
	struct ast_sip_session *session;
	struct ast_stream_topology *topology;
	const char *dest;
	int cause;
};

static int request(void *obj)
{
	struct request_data *req_data = obj;
	struct ast_sip_session *session = NULL;
	char *tmp = ast_strdupa(req_data->dest), *endpoint_name = NULL, *request_user = NULL;
	RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);

	AST_DECLARE_APP_ARGS(args,
		AST_APP_ARG(endpoint);
		AST_APP_ARG(aor);
	);

	if (ast_strlen_zero(tmp)) {
		ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty destination\n");
		req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
		return -1;
	}

	AST_NONSTANDARD_APP_ARGS(args, tmp, '/');

	if (ast_sip_get_disable_multi_domain()) {
		/* If a request user has been specified extract it from the endpoint name portion */
		if ((endpoint_name = strchr(args.endpoint, '@'))) {
			request_user = args.endpoint;
			*endpoint_name++ = '\0';
		} else {
			endpoint_name = args.endpoint;
		}

		if (ast_strlen_zero(endpoint_name)) {
			ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
			req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
			return -1;
		} else if (!(endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
			ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
			req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
			return -1;
		}
	} else {
		/* First try to find an exact endpoint match, for single (user) or multi-domain (user@domain) */
		endpoint_name = args.endpoint;
		if (ast_strlen_zero(endpoint_name)) {
			ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
			req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
			return -1;
		} else if (!(endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
			/* It seems it's not a multi-domain endpoint or single endpoint exact match,
			 * it's possible that it's a SIP trunk with a specified user (user@trunkname),
			 * so extract the user before @ sign.
			 */
			if ((endpoint_name = strchr(args.endpoint, '@'))) {
				request_user = args.endpoint;
				*endpoint_name++ = '\0';
			}

			if (ast_strlen_zero(endpoint_name)) {
				ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
				req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
				return -1;
			}

			if (!(endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
				ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
				req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
				return -1;
			}
		}
	}

	if (!(session = ast_sip_session_create_outgoing(endpoint, NULL, args.aor, request_user, req_data->topology))) {
		ast_log(LOG_ERROR, "Failed to create outgoing session to endpoint '%s'\n", endpoint_name);
		req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
		return -1;
	}

	req_data->session = session;

	return 0;
}

/*! \brief Function called by core to create a new outgoing PJSIP session */
static struct ast_channel *chan_pjsip_request_with_stream_topology(const char *type, struct ast_stream_topology *topology, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
{
	struct request_data req_data;
	RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);

	req_data.topology = topology;
	req_data.dest = data;
	/* Default failure value in case ast_sip_push_task_synchronous() itself fails. */
	req_data.cause = AST_CAUSE_FAILURE;

	if (ast_sip_push_task_synchronous(NULL, request, &req_data)) {
		*cause = req_data.cause;
		return NULL;
	}

	session = req_data.session;

	if (!(session->channel = chan_pjsip_new(session, AST_STATE_DOWN, NULL, NULL, assignedids, requestor, NULL))) {
		/* Session needs to be terminated prematurely */
		return NULL;
	}

	return session->channel;
}

static struct ast_channel *chan_pjsip_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
{
	struct ast_stream_topology *topology;
	struct ast_channel *chan;

	topology = ast_stream_topology_create_from_format_cap(cap);
	if (!topology) {
		return NULL;
	}

	chan = chan_pjsip_request_with_stream_topology(type, topology, assignedids, requestor, data, cause);

	ast_stream_topology_free(topology);

	return chan;
}

struct sendtext_data {
	struct ast_sip_session *session;
	char text[0];
};

static void sendtext_data_destroy(void *obj)
{
	struct sendtext_data *data = obj;
	ao2_ref(data->session, -1);
}

static struct sendtext_data* sendtext_data_create(struct ast_sip_session *session, const char *text)
{
	int size = strlen(text) + 1;
	struct sendtext_data *data = ao2_alloc(sizeof(*data)+size, sendtext_data_destroy);

	if (!data) {
		return NULL;
	}

	data->session = session;
	ao2_ref(data->session, +1);
	ast_copy_string(data->text, text, size);
	return data;
}

static int sendtext(void *obj)
{
	RAII_VAR(struct sendtext_data *, data, obj, ao2_cleanup);
	pjsip_tx_data *tdata;

	const struct ast_sip_body body = {
		.type = "text",
		.subtype = "plain",
		.body_text = data->text
	};

	if (data->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
		ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
			data->session->inv_session->cause,
			pjsip_get_status_text(data->session->inv_session->cause)->ptr);
	} else {
		ast_debug(3, "Sending in dialog SIP message\n");

		ast_sip_create_request("MESSAGE", data->session->inv_session->dlg, data->session->endpoint, NULL, NULL, &tdata);
		ast_sip_add_body(tdata, &body);
		ast_sip_send_request(tdata, data->session->inv_session->dlg, data->session->endpoint, NULL, NULL);
	}

#ifdef HAVE_PJSIP_INV_SESSION_REF
	pjsip_inv_dec_ref(data->session->inv_session);
#endif

	return 0;
}

/*! \brief Function called by core to send text on PJSIP session */
static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text)
{
	struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
	struct sendtext_data *data = sendtext_data_create(channel->session, text);

	if (!data) {
		return -1;
	}

#ifdef HAVE_PJSIP_INV_SESSION_REF
	if (pjsip_inv_add_ref(data->session->inv_session) != PJ_SUCCESS) {
		ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
		ao2_ref(data, -1);
		return -1;
	}
#endif

	if (ast_sip_push_task(channel->session->serializer, sendtext, data)) {
#ifdef HAVE_PJSIP_INV_SESSION_REF
		pjsip_inv_dec_ref(data->session->inv_session);
#endif
		ao2_ref(data, -1);
		return -1;
	}
	return 0;
}

/*! \brief Convert SIP hangup causes to Asterisk hangup causes */
static int hangup_sip2cause(int cause)
{
	/* Possible values taken from causes.h */

	switch(cause) {
	case 401:       /* Unauthorized */
		return AST_CAUSE_CALL_REJECTED;
	case 403:       /* Not found */
		return AST_CAUSE_CALL_REJECTED;
	case 404:       /* Not found */
		return AST_CAUSE_UNALLOCATED;
	case 405:       /* Method not allowed */
		return AST_CAUSE_INTERWORKING;
	case 407:       /* Proxy authentication required */
		return AST_CAUSE_CALL_REJECTED;
	case 408:       /* No reaction */
		return AST_CAUSE_NO_USER_RESPONSE;
	case 409:       /* Conflict */
		return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
	case 410:       /* Gone */
		return AST_CAUSE_NUMBER_CHANGED;
	case 411:       /* Length required */
		return AST_CAUSE_INTERWORKING;
	case 413:       /* Request entity too large */
		return AST_CAUSE_INTERWORKING;
	case 414:       /* Request URI too large */
		return AST_CAUSE_INTERWORKING;
	case 415:       /* Unsupported media type */
		return AST_CAUSE_INTERWORKING;
	case 420:       /* Bad extension */
		return AST_CAUSE_NO_ROUTE_DESTINATION;
	case 480:       /* No answer */
		return AST_CAUSE_NO_ANSWER;
	case 481:       /* No answer */
		return AST_CAUSE_INTERWORKING;
	case 482:       /* Loop detected */
		return AST_CAUSE_INTERWORKING;
	case 483:       /* Too many hops */
		return AST_CAUSE_NO_ANSWER;
	case 484:       /* Address incomplete */
		return AST_CAUSE_INVALID_NUMBER_FORMAT;
	case 485:       /* Ambiguous */
		return AST_CAUSE_UNALLOCATED;
	case 486:       /* Busy everywhere */
		return AST_CAUSE_BUSY;
	case 487:       /* Request terminated */
		return AST_CAUSE_INTERWORKING;
	case 488:       /* No codecs approved */
		return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
	case 491:       /* Request pending */
		return AST_CAUSE_INTERWORKING;
	case 493:       /* Undecipherable */
		return AST_CAUSE_INTERWORKING;
	case 500:       /* Server internal failure */
		return AST_CAUSE_FAILURE;
	case 501:       /* Call rejected */
		return AST_CAUSE_FACILITY_REJECTED;
	case 502:
		return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
	case 503:       /* Service unavailable */
		return AST_CAUSE_CONGESTION;
	case 504:       /* Gateway timeout */
		return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
	case 505:       /* SIP version not supported */
		return AST_CAUSE_INTERWORKING;
	case 600:       /* Busy everywhere */
		return AST_CAUSE_USER_BUSY;
	case 603:       /* Decline */
		return AST_CAUSE_CALL_REJECTED;
	case 604:       /* Does not exist anywhere */
		return AST_CAUSE_UNALLOCATED;
	case 606:       /* Not acceptable */
		return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
	default:
		if (cause < 500 && cause >= 400) {
			/* 4xx class error that is unknown - someting wrong with our request */
			return AST_CAUSE_INTERWORKING;
		} else if (cause < 600 && cause >= 500) {
			/* 5xx class error - problem in the remote end */
			return AST_CAUSE_CONGESTION;
		} else if (cause < 700 && cause >= 600) {
			/* 6xx - global errors in the 4xx class */
			return AST_CAUSE_INTERWORKING;
		}
		return AST_CAUSE_NORMAL;
	}
	/* Never reached */
	return 0;
}

static void chan_pjsip_session_begin(struct ast_sip_session *session)
{
	RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);

	if (session->endpoint->media.direct_media.glare_mitigation ==
			AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
		return;
	}

	datastore = ast_sip_session_alloc_datastore(&direct_media_mitigation_info,
			"direct_media_glare_mitigation");

	if (!datastore) {
		return;
	}

	ast_sip_session_add_datastore(session, datastore);
}

/*! \brief Function called when the session ends */
static void chan_pjsip_session_end(struct ast_sip_session *session)
{
	if (!session->channel) {
		return;
	}

	chan_pjsip_remove_hold(ast_channel_uniqueid(session->channel));

	ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
	if (!ast_channel_hangupcause(session->channel) && session->inv_session) {
		int cause = hangup_sip2cause(session->inv_session->cause);

		ast_queue_hangup_with_cause(session->channel, cause);
	} else {
		ast_queue_hangup(session->channel);
	}
}

/*! \brief Function called when a request is received on the session */
static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
{
	RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
	struct transport_info_data *transport_data;
	pjsip_tx_data *packet = NULL;

	if (session->channel) {
		return 0;
	}

	/* Check for a to-tag to determine if this is a reinvite */
	if (rdata->msg_info.to->tag.slen) {
		/* Weird case. We've received a reinvite but we don't have a channel. The most
		 * typical case for this happening is that a blind transfer fails, and so the
		 * transferer attempts to reinvite himself back into the call. We already got
		 * rid of that channel, and the other side of the call is unrecoverable.
		 *
		 * We treat this as a failure, so our best bet is to just hang this call
		 * up and not create a new channel. Clearing defer_terminate here ensures that
		 * calling ast_sip_session_terminate() can result in a BYE being sent ASAP.
		 */
		session->defer_terminate = 0;
		ast_sip_session_terminate(session, 400);
		return -1;
	}

	datastore = ast_sip_session_alloc_datastore(&transport_info, "transport_info");
	if (!datastore) {
		return -1;
	}

	transport_data = ast_calloc(1, sizeof(*transport_data));
	if (!transport_data) {
		return -1;
	}
	pj_sockaddr_cp(&transport_data->local_addr, &rdata->tp_info.transport->local_addr);
	pj_sockaddr_cp(&transport_data->remote_addr, &rdata->pkt_info.src_addr);
	datastore->data = transport_data;
	ast_sip_session_add_datastore(session, datastore);

	if (!(session->channel = chan_pjsip_new(session, AST_STATE_RING, session->exten, NULL, NULL, NULL, NULL))) {
		if (pjsip_inv_end_session(session->inv_session, 503, NULL, &packet) == PJ_SUCCESS
			&& packet) {
			ast_sip_session_send_response(session, packet);
		}

		ast_log(LOG_ERROR, "Failed to allocate new PJSIP channel on incoming SIP INVITE\n");
		return -1;
	}
	/* channel gets created on incoming request, but we wait to call start
           so other supplements have a chance to run */
	return 0;
}

static int call_pickup_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
{
	struct ast_features_pickup_config *pickup_cfg;
	struct ast_channel *chan;

	/* Check for a to-tag to determine if this is a reinvite */
	if (rdata->msg_info.to->tag.slen) {
		/* We don't care about reinvites */
		return 0;
	}

	pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
	if (!pickup_cfg) {
		ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension.\n");
		return 0;
	}

	if (strcmp(session->exten, pickup_cfg->pickupexten)) {
		ao2_ref(pickup_cfg, -1);
		return 0;
	}
	ao2_ref(pickup_cfg, -1);

	/* We can't directly use session->channel because the pickup operation will cause a masquerade to occur,
	 * changing the channel pointer in session to a different channel. To ensure we work on the right channel
	 * we store a pointer locally before we begin and keep a reference so it remains valid no matter what.
	 */
	chan = ast_channel_ref(session->channel);
	if (ast_pickup_call(chan)) {
		ast_channel_hangupcause_set(chan, AST_CAUSE_CALL_REJECTED);
	} else {
		ast_channel_hangupcause_set(chan, AST_CAUSE_NORMAL_CLEARING);
	}
	/* A hangup always occurs because the pickup operation will have either failed resulting in the call
	 * needing to be hung up OR the pickup operation was a success and the channel we now have is actually
	 * the channel that was replaced, which should be hung up since it is literally in limbo not connected
	 * to anything at all.
	 */
	ast_hangup(chan);
	ast_channel_unref(chan);

	return 1;
}

static struct ast_sip_session_supplement call_pickup_supplement = {
	.method = "INVITE",
	.priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST - 1,
	.incoming_request = call_pickup_incoming_request,
};

static int pbx_start_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
{
	int res;

	/* Check for a to-tag to determine if this is a reinvite */
	if (rdata->msg_info.to->tag.slen) {
		/* We don't care about reinvites */
		return 0;
	}

	res = ast_pbx_start(session->channel);

	switch (res) {
	case AST_PBX_FAILED:
		ast_log(LOG_WARNING, "Failed to start PBX ;(\n");
		ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
		ast_hangup(session->channel);
		break;
	case AST_PBX_CALL_LIMIT:
		ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
		ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
		ast_hangup(session->channel);
		break;
	case AST_PBX_SUCCESS:
	default:
		break;
	}

	ast_debug(3, "Started PBX on new PJSIP channel %s\n", ast_channel_name(session->channel));

	return (res == AST_PBX_SUCCESS) ? 0 : -1;
}

static struct ast_sip_session_supplement pbx_start_supplement = {
	.method = "INVITE",
	.priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST,
	.incoming_request = pbx_start_incoming_request,
};

/*! \brief Function called when a response is received on the session */
static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
{
	struct pjsip_status_line status = rdata->msg_info.msg->line.status;
	struct ast_control_pvt_cause_code *cause_code;
	int data_size = sizeof(*cause_code);

	if (!session->channel) {
		return;
	}

	/* Build and send the tech-specific cause information */
	/* size of the string making up the cause code is "SIP " number + " " + reason length */
	data_size += 4 + 4 + pj_strlen(&status.reason);
	cause_code = ast_alloca(data_size);
	memset(cause_code, 0, data_size);

	ast_copy_string(cause_code->chan_name, ast_channel_name(session->channel), AST_CHANNEL_NAME);

	snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "SIP %d %.*s", status.code,
	(int) pj_strlen(&status.reason), pj_strbuf(&status.reason));

	cause_code->ast_cause = hangup_sip2cause(status.code);
	ast_queue_control_data(session->channel, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
	ast_channel_hangupcause_hash_set(session->channel, cause_code, data_size);

	switch (status.code) {
	case 180:
		ast_queue_control(session->channel, AST_CONTROL_RINGING);
		ast_channel_lock(session->channel);
		if (ast_channel_state(session->channel) != AST_STATE_UP) {
			ast_setstate(session->channel, AST_STATE_RINGING);
		}
		ast_channel_unlock(session->channel);
		break;
	case 183:
		ast_queue_control(session->channel, AST_CONTROL_PROGRESS);
		break;
	case 200:
		ast_queue_control(session->channel, AST_CONTROL_ANSWER);
		break;
	default:
		break;
	}
}

static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
{
	if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD) {
		if (session->endpoint->media.direct_media.enabled && session->channel) {
			ast_queue_control(session->channel, AST_CONTROL_SRCCHANGE);
		}
	}
	return 0;
}

static int update_devstate(void *obj, void *arg, int flags)
{
	ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE,
			     "PJSIP/%s", ast_sorcery_object_get_id(obj));
	return 0;
}

static struct ast_custom_function chan_pjsip_dial_contacts_function = {
	.name = "PJSIP_DIAL_CONTACTS",
	.read = pjsip_acf_dial_contacts_read,
};

static struct ast_custom_function media_offer_function = {
	.name = "PJSIP_MEDIA_OFFER",
	.read = pjsip_acf_media_offer_read,
	.write = pjsip_acf_media_offer_write
};

static struct ast_custom_function dtmf_mode_function = {
	.name = "PJSIP_DTMF_MODE",
	.read = pjsip_acf_dtmf_mode_read,
	.write = pjsip_acf_dtmf_mode_write
};

static struct ast_custom_function session_refresh_function = {
	.name = "PJSIP_SEND_SESSION_REFRESH",
	.write = pjsip_acf_session_refresh_write,
};

/*!
 * \brief Load the module
 *
 * Module loading including tests for configuration or dependencies.
 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
 * configuration file or other non-critical problem return
 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
 */
static int load_module(void)
{
	struct ao2_container *endpoints;

	CHECK_PJSIP_SESSION_MODULE_LOADED();

	if (!(chan_pjsip_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
		return AST_MODULE_LOAD_DECLINE;
	}

	ast_format_cap_append_by_type(chan_pjsip_tech.capabilities, AST_MEDIA_TYPE_AUDIO);

	ast_rtp_glue_register(&chan_pjsip_rtp_glue);

	if (ast_channel_register(&chan_pjsip_tech)) {
		ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
		goto end;
	}

	if (ast_custom_function_register(&chan_pjsip_dial_contacts_function)) {
		ast_log(LOG_ERROR, "Unable to register PJSIP_DIAL_CONTACTS dialplan function\n");
		goto end;
	}

	if (ast_custom_function_register(&media_offer_function)) {
		ast_log(LOG_WARNING, "Unable to register PJSIP_MEDIA_OFFER dialplan function\n");
		goto end;
	}

	if (ast_custom_function_register(&dtmf_mode_function)) {
		ast_log(LOG_WARNING, "Unable to register PJSIP_DTMF_MODE dialplan function\n");
		goto end;
	}

	if (ast_custom_function_register(&session_refresh_function)) {
		ast_log(LOG_WARNING, "Unable to register PJSIP_SEND_SESSION_REFRESH dialplan function\n");
		goto end;
	}

	if (ast_sip_session_register_supplement(&chan_pjsip_supplement)) {
		ast_log(LOG_ERROR, "Unable to register PJSIP supplement\n");
		goto end;
	}

	if (!(pjsip_uids_onhold = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_RWLOCK,
			AO2_CONTAINER_ALLOC_OPT_DUPS_REJECT, 37, uid_hold_hash_fn,
			uid_hold_sort_fn, NULL))) {
		ast_log(LOG_ERROR, "Unable to create held channels container\n");
		goto end;
	}

	if (ast_sip_session_register_supplement(&call_pickup_supplement)) {
		ast_log(LOG_ERROR, "Unable to register PJSIP call pickup supplement\n");
		ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
		goto end;
	}

	if (ast_sip_session_register_supplement(&pbx_start_supplement)) {
		ast_log(LOG_ERROR, "Unable to register PJSIP pbx start supplement\n");
		ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
		ast_sip_session_unregister_supplement(&call_pickup_supplement);
		goto end;
	}

	if (ast_sip_session_register_supplement(&chan_pjsip_ack_supplement)) {
		ast_log(LOG_ERROR, "Unable to register PJSIP ACK supplement\n");
		ast_sip_session_unregister_supplement(&pbx_start_supplement);
		ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
		ast_sip_session_unregister_supplement(&call_pickup_supplement);
		goto end;
	}

	if (pjsip_channel_cli_register()) {
		ast_log(LOG_ERROR, "Unable to register PJSIP Channel CLI\n");
		ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
		ast_sip_session_unregister_supplement(&pbx_start_supplement);
		ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
		ast_sip_session_unregister_supplement(&call_pickup_supplement);
		goto end;
	}

	/* since endpoints are loaded before the channel driver their device
	   states get set to 'invalid', so they need to be updated */
	if ((endpoints = ast_sip_get_endpoints())) {
		ao2_callback(endpoints, OBJ_NODATA, update_devstate, NULL);
		ao2_ref(endpoints, -1);
	}

	return 0;

end:
	ao2_cleanup(pjsip_uids_onhold);
	pjsip_uids_onhold = NULL;
	ast_custom_function_unregister(&dtmf_mode_function);
	ast_custom_function_unregister(&media_offer_function);
	ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
	ast_custom_function_unregister(&session_refresh_function);
	ast_channel_unregister(&chan_pjsip_tech);
	ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);

	return AST_MODULE_LOAD_DECLINE;
}

/*! \brief Unload the PJSIP channel from Asterisk */
static int unload_module(void)
{
	ao2_cleanup(pjsip_uids_onhold);
	pjsip_uids_onhold = NULL;

	pjsip_channel_cli_unregister();

	ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
	ast_sip_session_unregister_supplement(&pbx_start_supplement);
	ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
	ast_sip_session_unregister_supplement(&call_pickup_supplement);

	ast_custom_function_unregister(&dtmf_mode_function);
	ast_custom_function_unregister(&media_offer_function);
	ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
	ast_custom_function_unregister(&session_refresh_function);

	ast_channel_unregister(&chan_pjsip_tech);
	ao2_ref(chan_pjsip_tech.capabilities, -1);
	ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);

	return 0;
}

AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Channel Driver",
	.support_level = AST_MODULE_SUPPORT_CORE,
	.load = load_module,
	.unload = unload_module,
	.load_pri = AST_MODPRI_CHANNEL_DRIVER,
);