summaryrefslogtreecommitdiff
path: root/main/channel.c
blob: 8325f19c3595401a6b6586c923b26f7e9e1262c6 (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
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
/*
 * Asterisk -- An open source telephony toolkit.
 *
 * Copyright (C) 1999 - 2006, Digium, Inc.
 *
 * Mark Spencer <markster@digium.com>
 *
 * See http://www.asterisk.org for more information about
 * the Asterisk project. Please do not directly contact
 * any of the maintainers of this project for assistance;
 * the project provides a web site, mailing lists and IRC
 * channels for your use.
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License Version 2. See the LICENSE file
 * at the top of the source tree.
 */

/*! \file
 *
 * \brief Channel Management
 *
 * \author Mark Spencer <markster@digium.com>
 */

/*** MODULEINFO
	<support_level>core</support_level>
 ***/

#include "asterisk.h"

#include "asterisk/_private.h"

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

#include "asterisk/paths.h"	/* use ast_config_AST_SYSTEM_NAME */

#include "asterisk/pbx.h"
#include "asterisk/frame.h"
#include "asterisk/mod_format.h"
#include "asterisk/sched.h"
#include "asterisk/channel.h"
#include "asterisk/musiconhold.h"
#include "asterisk/say.h"
#include "asterisk/file.h"
#include "asterisk/cli.h"
#include "asterisk/translate.h"
#include "asterisk/manager.h"
#include "asterisk/chanvars.h"
#include "asterisk/linkedlists.h"
#include "asterisk/indications.h"
#include "asterisk/causes.h"
#include "asterisk/callerid.h"
#include "asterisk/utils.h"
#include "asterisk/lock.h"
#include "asterisk/app.h"
#include "asterisk/transcap.h"
#include "asterisk/devicestate.h"
#include "asterisk/threadstorage.h"
#include "asterisk/slinfactory.h"
#include "asterisk/audiohook.h"
#include "asterisk/framehook.h"
#include "asterisk/timing.h"
#include "asterisk/autochan.h"
#include "asterisk/stringfields.h"
#include "asterisk/global_datastores.h"
#include "asterisk/channel_internal.h"
#include "asterisk/features.h"
#include "asterisk/bridge.h"
#include "asterisk/test.h"
#include "asterisk/stasis_channels.h"
#include "asterisk/max_forwards.h"
#include "asterisk/stream.h"

/*** DOCUMENTATION
 ***/

#if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
#if defined(HAVE_PRI)
#include "libpri.h"
#endif	/* defined(HAVE_PRI) */
#endif	/* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */

/* uncomment if you have problems with 'monitoring' synchronized files */
#if 0
#define MONITOR_CONSTANT_DELAY
#define MONITOR_DELAY	150 * 8		/*!< 150 ms of MONITORING DELAY */
#endif

static int chancount;

unsigned long global_fin, global_fout;

AST_THREADSTORAGE(state2str_threadbuf);
#define STATE2STR_BUFSIZE   32

/*! Default amount of time to use when emulating a digit as a begin and end
 *  100ms */
#define AST_DEFAULT_EMULATE_DTMF_DURATION 100

#define DEFAULT_AMA_FLAGS AST_AMA_DOCUMENTATION

/*! Minimum amount of time between the end of the last digit and the beginning
 *  of a new one - 45ms */
#define AST_MIN_DTMF_GAP 45

/*! \brief List of channel drivers */
struct chanlist {
	const struct ast_channel_tech *tech;
	AST_LIST_ENTRY(chanlist) list;
};

/*! \brief the list of registered channel types */
static AST_RWLIST_HEAD_STATIC(backends, chanlist);

#ifdef LOW_MEMORY
#define NUM_CHANNEL_BUCKETS 61
#else
#define NUM_CHANNEL_BUCKETS 1567
#endif

/*! \brief All active channels on the system */
static struct ao2_container *channels;

/*! \brief map AST_CAUSE's to readable string representations
 *
 * \ref causes.h
*/
struct causes_map {
	int cause;
	const char *name;
	const char *desc;
};

static const struct causes_map causes[] = {
	{ AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
	{ AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
	{ AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
	{ AST_CAUSE_MISDIALLED_TRUNK_PREFIX, "MISDIALLED_TRUNK_PREFIX", "Misdialed trunk prefix" },
	{ AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
	{ AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
	{ AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
	{ AST_CAUSE_NUMBER_PORTED_NOT_HERE, "NUMBER_PORTED_NOT_HERE", "Number ported elsewhere" },
	{ AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
	{ AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
	{ AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
	{ AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
	{ AST_CAUSE_SUBSCRIBER_ABSENT, "SUBSCRIBER_ABSENT", "Subscriber absent" },
	{ AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
	{ AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
	{ AST_CAUSE_REDIRECTED_TO_NEW_DESTINATION, "REDIRECTED_TO_NEW_DESTINATION", "Redirected to new destination" },
	{ AST_CAUSE_ANSWERED_ELSEWHERE, "ANSWERED_ELSEWHERE", "Answered elsewhere" },
	{ AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
	{ AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
	{ AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
	{ AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
	{ AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
	{ AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
	{ AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
	{ AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
	{ AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
	{ AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
	{ AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
	{ AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
	{ AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
	{ AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
	{ AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
	{ AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
	{ AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
	{ AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
	{ AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
	{ AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
	{ AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
	{ AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
	{ AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
	{ AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
	{ AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
	{ AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
	{ AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
	{ AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
	{ AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
	{ AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
	{ AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
	{ AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
};

struct ast_variable *ast_channeltype_list(void)
{
	struct chanlist *cl;
	struct ast_variable *var = NULL, *prev = NULL;

	AST_RWLIST_RDLOCK(&backends);
	AST_RWLIST_TRAVERSE(&backends, cl, list) {
		if (prev)  {
			if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
				prev = prev->next;
		} else {
			var = ast_variable_new(cl->tech->type, cl->tech->description, "");
			prev = var;
		}
	}
	AST_RWLIST_UNLOCK(&backends);

	return var;
}

#if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
static const char *party_number_ton2str(int ton)
{
#if defined(HAVE_PRI)
	switch ((ton >> 4) & 0x07) {
	case PRI_TON_INTERNATIONAL:
		return "International";
	case PRI_TON_NATIONAL:
		return "National";
	case PRI_TON_NET_SPECIFIC:
		return "Network Specific";
	case PRI_TON_SUBSCRIBER:
		return "Subscriber";
	case PRI_TON_ABBREVIATED:
		return "Abbreviated";
	case PRI_TON_RESERVED:
		return "Reserved";
	case PRI_TON_UNKNOWN:
	default:
		break;
	}
#endif	/* defined(HAVE_PRI) */
	return "Unknown";
}
#endif	/* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */

#if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
static const char *party_number_plan2str(int plan)
{
#if defined(HAVE_PRI)
	switch (plan & 0x0F) {
	default:
	case PRI_NPI_UNKNOWN:
		break;
	case PRI_NPI_E163_E164:
		return "Public (E.163/E.164)";
	case PRI_NPI_X121:
		return "Data (X.121)";
	case PRI_NPI_F69:
		return "Telex (F.69)";
	case PRI_NPI_NATIONAL:
		return "National Standard";
	case PRI_NPI_PRIVATE:
		return "Private";
	case PRI_NPI_RESERVED:
		return "Reserved";
	}
#endif	/* defined(HAVE_PRI) */
	return "Unknown";
}
#endif	/* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */

/*! \brief Show channel types - CLI command */
static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
#define FORMAT  "%-15.15s  %-40.40s %-13.13s %-13.13s %-13.13s %-13.13s\n"
	struct chanlist *cl;
	int count_chan = 0;

	switch (cmd) {
	case CLI_INIT:
		e->command = "core show channeltypes";
		e->usage =
			"Usage: core show channeltypes\n"
			"       Lists available channel types registered in your\n"
			"       Asterisk server.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

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

	ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Presencestate", "Indications", "Transfer");
	ast_cli(a->fd, FORMAT, "-------------", "-------------", "-------------", "-------------", "-------------", "-------------");

	AST_RWLIST_RDLOCK(&backends);
	AST_RWLIST_TRAVERSE(&backends, cl, list) {
		ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
			(cl->tech->devicestate) ? "yes" : "no",
			(cl->tech->presencestate) ? "yes" : "no",
			(cl->tech->indicate) ? "yes" : "no",
			(cl->tech->transfer) ? "yes" : "no");
		count_chan++;
	}
	AST_RWLIST_UNLOCK(&backends);

	ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);

	return CLI_SUCCESS;

#undef FORMAT
}

static char *complete_channeltypes(struct ast_cli_args *a)
{
	struct chanlist *cl;
	int wordlen;

	if (a->pos != 3) {
		return NULL;
	}

	wordlen = strlen(a->word);

	AST_RWLIST_RDLOCK(&backends);
	AST_RWLIST_TRAVERSE(&backends, cl, list) {
		if (!strncasecmp(a->word, cl->tech->type, wordlen)) {
			ast_cli_completion_add(ast_strdup(cl->tech->type));
		}
	}
	AST_RWLIST_UNLOCK(&backends);

	return NULL;
}

/*! \brief Show details about a channel driver - CLI command */
static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	struct chanlist *cl = NULL;
	struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);

	switch (cmd) {
	case CLI_INIT:
		e->command = "core show channeltype";
		e->usage =
			"Usage: core show channeltype <name>\n"
			"	Show details about the specified channel type, <name>.\n";
		return NULL;
	case CLI_GENERATE:
		return complete_channeltypes(a);
	}

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

	AST_RWLIST_RDLOCK(&backends);

	AST_RWLIST_TRAVERSE(&backends, cl, list) {
		if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
			break;
	}


	if (!cl) {
		ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
		AST_RWLIST_UNLOCK(&backends);
		return CLI_FAILURE;
	}

	ast_cli(a->fd,
		"-- Info about channel driver: %s --\n"
		"  Device State: %s\n"
		"Presence State: %s\n"
		"    Indication: %s\n"
		"     Transfer : %s\n"
		"  Capabilities: %s\n"
		"   Digit Begin: %s\n"
		"     Digit End: %s\n"
		"    Send HTML : %s\n"
		" Image Support: %s\n"
		"  Text Support: %s\n",
		cl->tech->type,
		(cl->tech->devicestate) ? "yes" : "no",
		(cl->tech->presencestate) ? "yes" : "no",
		(cl->tech->indicate) ? "yes" : "no",
		(cl->tech->transfer) ? "yes" : "no",
		ast_format_cap_get_names(cl->tech->capabilities, &codec_buf),
		(cl->tech->send_digit_begin) ? "yes" : "no",
		(cl->tech->send_digit_end) ? "yes" : "no",
		(cl->tech->send_html) ? "yes" : "no",
		(cl->tech->send_image) ? "yes" : "no",
		(cl->tech->send_text) ? "yes" : "no"

	);

	AST_RWLIST_UNLOCK(&backends);

	return CLI_SUCCESS;
}

static struct ast_cli_entry cli_channel[] = {
	AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
	AST_CLI_DEFINE(handle_cli_core_show_channeltype,  "Give more details on that channel type")
};

static struct ast_frame *kill_read(struct ast_channel *chan)
{
	/* Hangup channel. */
	return NULL;
}

static struct ast_frame *kill_exception(struct ast_channel *chan)
{
	/* Hangup channel. */
	return NULL;
}

static int kill_write(struct ast_channel *chan, struct ast_frame *frame)
{
	/* Hangup channel. */
	return -1;
}

static int kill_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
{
	/* No problem fixing up the channel. */
	return 0;
}

static int kill_hangup(struct ast_channel *chan)
{
	ast_channel_tech_pvt_set(chan, NULL);
	return 0;
}

/*!
 * \brief Kill the channel channel driver technology descriptor.
 *
 * \details
 * The purpose of this channel technology is to encourage the
 * channel to hangup as quickly as possible.
 *
 * \note Used by DTMF atxfer and zombie channels.
 */
const struct ast_channel_tech ast_kill_tech = {
	.type = "Kill",
	.description = "Kill channel (should not see this)",
	.read = kill_read,
	.exception = kill_exception,
	.write = kill_write,
	.fixup = kill_fixup,
	.hangup = kill_hangup,
};

/*! \brief Checks to see if a channel is needing hang up */
int ast_check_hangup(struct ast_channel *chan)
{
	if (ast_channel_softhangup_internal_flag(chan))		/* yes if soft hangup flag set */
		return 1;
	if (ast_tvzero(*ast_channel_whentohangup(chan)))	/* no if no hangup scheduled */
		return 0;
	if (ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()) > 0)		/* no if hangup time has not come yet. */
		return 0;
	ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()));
	ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(chan));
	ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);	/* record event */
	return 1;
}

int ast_check_hangup_locked(struct ast_channel *chan)
{
	int res;
	ast_channel_lock(chan);
	res = ast_check_hangup(chan);
	ast_channel_unlock(chan);
	return res;
}

void ast_channel_softhangup_withcause_locked(struct ast_channel *chan, int causecode)
{
	ast_channel_lock(chan);

	if (causecode > 0) {
		ast_debug(1, "Setting hangupcause of channel %s to %d (is %d now)\n",
			ast_channel_name(chan), causecode, ast_channel_hangupcause(chan));

		ast_channel_hangupcause_set(chan, causecode);
	}

	ast_softhangup_nolock(chan, AST_SOFTHANGUP_EXPLICIT);

	ast_channel_unlock(chan);
}

static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
{
	struct ast_channel *chan = obj;

	ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);

	return 0;
}

void ast_softhangup_all(void)
{
	ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
}

/*! \brief returns number of active/allocated channels */
int ast_active_channels(void)
{
	return channels ? ao2_container_count(channels) : 0;
}

int ast_undestroyed_channels(void)
{
	return ast_atomic_fetchadd_int(&chancount, 0);
}

/*! \brief Set when to hangup channel */
void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
{
	if (ast_tvzero(offset)) {
		ast_channel_whentohangup_set(chan, &offset);
	} else {
		struct timeval tv = ast_tvadd(offset, ast_tvnow());
		ast_channel_whentohangup_set(chan, &tv);
	}
	ast_queue_frame(chan, &ast_null_frame);
	return;
}

void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
{
	struct timeval when = { offset, };
	ast_channel_setwhentohangup_tv(chan, when);
}

/*! \brief Compare a offset with when to hangup channel */
int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
{
	struct timeval whentohangup;

	if (ast_tvzero(*ast_channel_whentohangup(chan)))
		return ast_tvzero(offset) ? 0 : -1;

	if (ast_tvzero(offset))
		return 1;

	whentohangup = ast_tvadd(offset, ast_tvnow());

	return ast_tvdiff_ms(whentohangup, *ast_channel_whentohangup(chan));
}

int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
{
	struct timeval when = { offset, };
	return ast_channel_cmpwhentohangup_tv(chan, when);
}

/*! \brief Register a new telephony channel in Asterisk */
int ast_channel_register(const struct ast_channel_tech *tech)
{
	struct chanlist *chan;

	AST_RWLIST_WRLOCK(&backends);

	AST_RWLIST_TRAVERSE(&backends, chan, list) {
		if (!strcasecmp(tech->type, chan->tech->type)) {
			ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
			AST_RWLIST_UNLOCK(&backends);
			return -1;
		}
	}

	if (!(chan = ast_calloc(1, sizeof(*chan)))) {
		AST_RWLIST_UNLOCK(&backends);
		return -1;
	}
	chan->tech = tech;
	AST_RWLIST_INSERT_HEAD(&backends, chan, list);

	ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);

	ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);

	AST_RWLIST_UNLOCK(&backends);

	return 0;
}

/*! \brief Unregister channel driver */
void ast_channel_unregister(const struct ast_channel_tech *tech)
{
	struct chanlist *chan;

	ast_debug(1, "Unregistering channel type '%s'\n", tech->type);

	AST_RWLIST_WRLOCK(&backends);

	AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
		if (chan->tech == tech) {
			AST_LIST_REMOVE_CURRENT(list);
			ast_free(chan);
			ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
			break;
		}
	}
	AST_LIST_TRAVERSE_SAFE_END;

	AST_RWLIST_UNLOCK(&backends);
}

/*! \brief Get handle to channel driver based on name */
const struct ast_channel_tech *ast_get_channel_tech(const char *name)
{
	struct chanlist *chanls;
	const struct ast_channel_tech *ret = NULL;

	AST_RWLIST_RDLOCK(&backends);

	AST_RWLIST_TRAVERSE(&backends, chanls, list) {
		if (!strcasecmp(name, chanls->tech->type)) {
			ret = chanls->tech;
			break;
		}
	}

	AST_RWLIST_UNLOCK(&backends);

	return ret;
}

/*! \brief Gives the string form of a given hangup cause */
const char *ast_cause2str(int cause)
{
	int x;

	for (x = 0; x < ARRAY_LEN(causes); x++) {
		if (causes[x].cause == cause)
			return causes[x].desc;
	}

	return "Unknown";
}

/*! \brief Convert a symbolic hangup cause to number */
int ast_str2cause(const char *name)
{
	int x;

	for (x = 0; x < ARRAY_LEN(causes); x++)
		if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
			return causes[x].cause;

	return -1;
}

static struct stasis_message *create_channel_snapshot_message(struct ast_channel *channel)
{
	RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);

	if (!ast_channel_snapshot_type()) {
		return NULL;
	}

	ast_channel_lock(channel);
	snapshot = ast_channel_snapshot_create(channel);
	ast_channel_unlock(channel);
	if (!snapshot) {
		return NULL;
	}

	return stasis_message_create(ast_channel_snapshot_type(), snapshot);
}

static void publish_cache_clear(struct ast_channel *chan)
{
	RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
	RAII_VAR(struct stasis_message *, clear_msg, NULL, ao2_cleanup);

	clear_msg = create_channel_snapshot_message(chan);
	if (!clear_msg) {
		return;
	}

	message = stasis_cache_clear_create(clear_msg);
	stasis_publish(ast_channel_topic(chan), message);
}

/*! \brief Gives the string form of a given channel state.
 *
 * \note This function is not reentrant.
 *
 * \param state
 */
const char *ast_state2str(enum ast_channel_state state)
{
	char *buf;

	switch (state) {
	case AST_STATE_DOWN:
		return "Down";
	case AST_STATE_RESERVED:
		return "Rsrvd";
	case AST_STATE_OFFHOOK:
		return "OffHook";
	case AST_STATE_DIALING:
		return "Dialing";
	case AST_STATE_RING:
		return "Ring";
	case AST_STATE_RINGING:
		return "Ringing";
	case AST_STATE_UP:
		return "Up";
	case AST_STATE_BUSY:
		return "Busy";
	case AST_STATE_DIALING_OFFHOOK:
		return "Dialing Offhook";
	case AST_STATE_PRERING:
		return "Pre-ring";
	case AST_STATE_MUTE:
		return "Mute";
	default:
		if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
			return "Unknown";
		snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%u)", state);
		return buf;
	}
}

/*! \brief Gives the string form of a given transfer capability */
char *ast_transfercapability2str(int transfercapability)
{
	switch (transfercapability) {
	case AST_TRANS_CAP_SPEECH:
		return "SPEECH";
	case AST_TRANS_CAP_DIGITAL:
		return "DIGITAL";
	case AST_TRANS_CAP_RESTRICTED_DIGITAL:
		return "RESTRICTED_DIGITAL";
	case AST_TRANS_CAP_3_1K_AUDIO:
		return "3K1AUDIO";
	case AST_TRANS_CAP_DIGITAL_W_TONES:
		return "DIGITAL_W_TONES";
	case AST_TRANS_CAP_VIDEO:
		return "VIDEO";
	default:
		return "UNKNOWN";
	}
}

/*! \brief Channel technology used to extract a channel from a running application. The
 * channel created with this technology will be immediately hung up - most external
 * applications won't ever want to see this.
 */
static const struct ast_channel_tech surrogate_tech = {
	.type = "Surrogate",
	.description = "Surrogate channel used to pull channel from an application",
	.properties = AST_CHAN_TP_INTERNAL,
};

static const struct ast_channel_tech null_tech = {
	.type = "NULL",
	.description = "Null channel (should not see this)",
};

static void ast_channel_destructor(void *obj);
static void ast_dummy_channel_destructor(void *obj);
static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags);

static int does_id_conflict(const char *uniqueid)
{
	struct ast_channel *conflict;
	int length = 0;

	if (ast_strlen_zero(uniqueid)) {
		return 0;
	}

	conflict = ast_channel_callback(ast_channel_by_uniqueid_cb, (char *) uniqueid, &length, OBJ_NOLOCK);
	if (conflict) {
		ast_log(LOG_ERROR, "Channel Unique ID '%s' already in use by channel %s(%p)\n",
			uniqueid, ast_channel_name(conflict), conflict);
		ast_channel_unref(conflict);
		return 1;
	}

	return 0;
}

/*! \brief Create a new channel structure */
static struct ast_channel *__attribute__((format(printf, 15, 0)))
__ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
		       const char *acctcode, const char *exten, const char *context, const struct ast_assigned_ids *assignedids,
		       const struct ast_channel *requestor, enum ama_flags amaflag, struct ast_endpoint *endpoint,
		       const char *file, int line,
		       const char *function, const char *name_fmt, va_list ap)
{
	struct ast_channel *tmp;
	struct varshead *headp;
	char *tech = "", *tech2 = NULL;
	struct ast_format_cap *nativeformats;
	struct ast_sched_context *schedctx;
	struct ast_timer *timer;
	struct timeval now;
	const struct ast_channel_tech *channel_tech;
	struct ast_stream_topology *topology;

	/* If shutting down, don't allocate any new channels */
	if (ast_shutting_down()) {
		ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
		return NULL;
	}

	tmp = __ast_channel_internal_alloc(ast_channel_destructor, assignedids, requestor,
		file, line, function);
	if (!tmp) {
		/* Channel structure allocation failure. */
		return NULL;
	}

	ast_channel_stage_snapshot(tmp);

	if (!(nativeformats = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
		/*
		 * Aborting the channel creation.  We do not need to complete staging
		 * the channel snapshot because the channel has not been finalized or
		 * linked into the channels container yet.  Nobody else knows about
		 * this channel nor will anybody ever know about it.
		 */
		return ast_channel_unref(tmp);
	}
	ast_format_cap_append(nativeformats, ast_format_none, 0);
	ast_channel_nativeformats_set(tmp, nativeformats);
	ao2_ref(nativeformats, -1);

	ast_channel_set_rawwriteformat(tmp, ast_format_none);
	ast_channel_set_rawreadformat(tmp, ast_format_none);
	ast_channel_set_writeformat(tmp, ast_format_none);
	ast_channel_set_readformat(tmp, ast_format_none);

	/*
	 * Init file descriptors to unopened state so
	 * the destructor can know not to close them.
	 */
	ast_channel_timingfd_set(tmp, -1);
	ast_channel_internal_alertpipe_clear(tmp);
	ast_channel_internal_fd_clear_all(tmp);

	if (!(schedctx = ast_sched_context_create())) {
		ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
		/* See earlier channel creation abort comment above. */
		return ast_channel_unref(tmp);
	}
	ast_channel_sched_set(tmp, schedctx);

	ast_party_dialed_init(ast_channel_dialed(tmp));
	ast_party_caller_init(ast_channel_caller(tmp));
	ast_party_connected_line_init(ast_channel_connected(tmp));
	ast_party_connected_line_init(ast_channel_connected_indicated(tmp));
	ast_party_redirecting_init(ast_channel_redirecting(tmp));

	if (cid_name) {
		ast_channel_caller(tmp)->id.name.valid = 1;
		ast_channel_caller(tmp)->id.name.str = ast_strdup(cid_name);
		if (!ast_channel_caller(tmp)->id.name.str) {
			/* See earlier channel creation abort comment above. */
			return ast_channel_unref(tmp);
		}
	}
	if (cid_num) {
		ast_channel_caller(tmp)->id.number.valid = 1;
		ast_channel_caller(tmp)->id.number.str = ast_strdup(cid_num);
		if (!ast_channel_caller(tmp)->id.number.str) {
			/* See earlier channel creation abort comment above. */
			return ast_channel_unref(tmp);
		}
	}

	if ((timer = ast_timer_open())) {
		ast_channel_timer_set(tmp, timer);
		if (strcmp(ast_timer_get_name(ast_channel_timer(tmp)), "timerfd")) {
			needqueue = 0;
		}
		ast_channel_timingfd_set(tmp, ast_timer_fd(ast_channel_timer(tmp)));
	}

	if (needqueue && ast_channel_internal_alertpipe_init(tmp)) {
		/* See earlier channel creation abort comment above. */
		return ast_channel_unref(tmp);
	}

	if (!(topology = ast_stream_topology_alloc())) {
		return ast_channel_unref(tmp);
	}
	ast_channel_internal_set_stream_topology(tmp, topology);

	/* Always watch the alertpipe */
	ast_channel_set_fd(tmp, AST_ALERT_FD, ast_channel_internal_alert_readfd(tmp));
	/* And timing pipe */
	ast_channel_set_fd(tmp, AST_TIMING_FD, ast_channel_timingfd(tmp));

	/* Initial state */
	ast_channel_state_set(tmp, state);
	ast_channel_hold_state_set(tmp, AST_CONTROL_UNHOLD);

	ast_channel_streamid_set(tmp, -1);
	ast_channel_vstreamid_set(tmp, -1);

	ast_channel_fin_set(tmp, global_fin);
	ast_channel_fout_set(tmp, global_fout);

	now = ast_tvnow();
	ast_channel_creationtime_set(tmp, &now);

	ast_channel_internal_setup_topics(tmp);

	if (!ast_strlen_zero(name_fmt)) {
		char *slash, *slash2;
		/* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
		 * And they all use slightly different formats for their name string.
		 * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
		 * This means, that the stringfields must have a routine that takes the va_lists directly, and
		 * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
		 * This new function was written so this can be accomplished.
		 */
		ast_channel_name_build_va(tmp, name_fmt, ap);
		tech = ast_strdupa(ast_channel_name(tmp));
		if ((slash = strchr(tech, '/'))) {
			if ((slash2 = strchr(slash + 1, '/'))) {
				tech2 = slash + 1;
				*slash2 = '\0';
			}
			*slash = '\0';
		}
	} else {
		/*
		 * Start the string with '-' so it becomes an empty string
		 * in the destructor.
		 */
		ast_channel_name_set(tmp, "-**Unknown**");
	}

	if (amaflag != AST_AMA_NONE) {
		ast_channel_amaflags_set(tmp, amaflag);
	} else {
		ast_channel_amaflags_set(tmp, DEFAULT_AMA_FLAGS);
	}

	if (!ast_strlen_zero(acctcode)) {
		ast_channel_accountcode_set(tmp, acctcode);
	}
	ast_channel_language_set(tmp, ast_defaultlanguage);

	ast_channel_context_set(tmp, S_OR(context, "default"));
	ast_channel_exten_set(tmp, S_OR(exten, "s"));
	ast_channel_priority_set(tmp, 1);

	headp = ast_channel_varshead(tmp);
	AST_LIST_HEAD_INIT_NOLOCK(headp);

	ast_pbx_hangup_handler_init(tmp);
	AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
	AST_LIST_HEAD_INIT_NOLOCK(ast_channel_autochans(tmp));

	channel_tech = ast_get_channel_tech(tech);
	if (!channel_tech && !ast_strlen_zero(tech2)) {
		channel_tech = ast_get_channel_tech(tech2);
	}
	if (channel_tech) {
		ast_channel_tech_set(tmp, channel_tech);
	} else {
		ast_channel_tech_set(tmp, &null_tech);
	}

	/* You might scream "locking inversion" at seeing this but it is actually perfectly fine.
	 * Since the channel was just created nothing can know about it yet or even acquire it.
	 */
	ast_channel_lock(tmp);

	ao2_lock(channels);

	if (assignedids && (does_id_conflict(assignedids->uniqueid) || does_id_conflict(assignedids->uniqueid2))) {
		ast_channel_internal_errno_set(AST_CHANNEL_ERROR_ID_EXISTS);
		ao2_unlock(channels);
		ast_channel_unlock(tmp);
		/* See earlier channel creation abort comment above. */
		return ast_channel_unref(tmp);
	}

	/* Finalize and link into the channels container. */
	ast_channel_internal_finalize(tmp);
	ast_atomic_fetchadd_int(&chancount, +1);
	ao2_link_flags(channels, tmp, OBJ_NOLOCK);

	ao2_unlock(channels);

	if (endpoint) {
		ast_endpoint_add_channel(endpoint, tmp);
	}

	/*
	 * And now, since the channel structure is built, and has its name, let
	 * the world know of its existance
	 */
	ast_channel_stage_snapshot_done(tmp);

	ast_debug(1, "Channel %p '%s' allocated\n", tmp, ast_channel_name(tmp));

	return tmp;
}

struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
					const char *cid_name, const char *acctcode,
					const char *exten, const char *context, const struct ast_assigned_ids *assignedids,
					const struct ast_channel *requestor, enum ama_flags amaflag,
					struct ast_endpoint *endpoint,
					const char *file, int line, const char *function,
					const char *name_fmt, ...)
{
	va_list ap;
	struct ast_channel *result;

	va_start(ap, name_fmt);
	result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
					assignedids, requestor, amaflag, endpoint, file, line, function, name_fmt, ap);
	va_end(ap);

	return result;
}

/* only do the minimum amount of work needed here to make a channel
 * structure that can be used to expand channel vars */
struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
{
	struct ast_channel *tmp;
	struct varshead *headp;

	tmp = __ast_channel_internal_alloc(ast_dummy_channel_destructor, NULL, NULL,
		file, line, function);
	if (!tmp) {
		/* Dummy channel structure allocation failure. */
		return NULL;
	}

	ast_pbx_hangup_handler_init(tmp);
	AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));

	/*
	 * Init file descriptors to unopened state just in case
	 * autoservice is called on the channel or something tries to
	 * read a frame from it.
	 */
	ast_channel_timingfd_set(tmp, -1);
	ast_channel_internal_alertpipe_clear(tmp);
	ast_channel_internal_fd_clear_all(tmp);

	ast_channel_hold_state_set(tmp, AST_CONTROL_UNHOLD);

	ast_channel_internal_setup_topics(tmp);

	headp = ast_channel_varshead(tmp);
	AST_LIST_HEAD_INIT_NOLOCK(headp);

	return tmp;
}

static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
{
	struct ast_frame *f;
	struct ast_frame *cur;
	unsigned int new_frames = 0;
	unsigned int new_voice_frames = 0;
	unsigned int queued_frames = 0;
	unsigned int queued_voice_frames = 0;
	AST_LIST_HEAD_NOLOCK(,ast_frame) frames;

	ast_channel_lock(chan);

	/*
	 * Check the last frame on the queue if we are queuing the new
	 * frames after it.
	 */
	cur = AST_LIST_LAST(ast_channel_readq(chan));
	if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
		switch (cur->subclass.integer) {
		case AST_CONTROL_END_OF_Q:
			if (fin->frametype == AST_FRAME_CONTROL
				&& fin->subclass.integer == AST_CONTROL_HANGUP) {
				/*
				 * Destroy the end-of-Q marker frame so we can queue the hangup
				 * frame in its place.
				 */
				AST_LIST_REMOVE(ast_channel_readq(chan), cur, frame_list);
				ast_frfree(cur);

				/*
				 * This has degenerated to a normal queue append anyway.  Since
				 * we just destroyed the last frame in the queue we must make
				 * sure that "after" is NULL or bad things will happen.
				 */
				after = NULL;
				break;
			}
			/* Fall through */
		case AST_CONTROL_HANGUP:
			/* Don't queue anything. */
			ast_channel_unlock(chan);
			return 0;
		default:
			break;
		}
	}

	/* Build copies of all the new frames and count them */
	AST_LIST_HEAD_INIT_NOLOCK(&frames);
	for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
		if (!(f = ast_frdup(cur))) {
			if (AST_LIST_FIRST(&frames)) {
				ast_frfree(AST_LIST_FIRST(&frames));
			}
			ast_channel_unlock(chan);
			return -1;
		}

		AST_LIST_INSERT_TAIL(&frames, f, frame_list);
		new_frames++;
		if (f->frametype == AST_FRAME_VOICE) {
			new_voice_frames++;
		}
	}

	/* Count how many frames exist on the queue */
	AST_LIST_TRAVERSE(ast_channel_readq(chan), cur, frame_list) {
		queued_frames++;
		if (cur->frametype == AST_FRAME_VOICE) {
			queued_voice_frames++;
		}
	}

	if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
		int count = 0;
		ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
		AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), cur, frame_list) {
			/* Save the most recent frame */
			if (!AST_LIST_NEXT(cur, frame_list)) {
				break;
			} else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
				if (++count > 64) {
					break;
				}
				AST_LIST_REMOVE_CURRENT(frame_list);
				ast_frfree(cur);

				/* Read from the alert pipe for each flushed frame. */
				ast_channel_internal_alert_read(chan);
			}
		}
		AST_LIST_TRAVERSE_SAFE_END;
	}

	if (after) {
		AST_LIST_INSERT_LIST_AFTER(ast_channel_readq(chan), &frames, after, frame_list);
	} else {
		if (head) {
			AST_LIST_APPEND_LIST(&frames, ast_channel_readq(chan), frame_list);
			AST_LIST_HEAD_INIT_NOLOCK(ast_channel_readq(chan));
		}
		AST_LIST_APPEND_LIST(ast_channel_readq(chan), &frames, frame_list);
	}

	if (ast_channel_alert_writable(chan)) {
		/* Write to the alert pipe for each added frame */
		while (new_frames--) {
			if (ast_channel_alert_write(chan)) {
				ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %u): %s!\n",
					ast_channel_name(chan), queued_frames, strerror(errno));
				break;
			}
		}
	} else if (ast_channel_timingfd(chan) > -1) {
		ast_timer_enable_continuous(ast_channel_timer(chan));
	} else if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
		pthread_kill(ast_channel_blocker(chan), SIGURG);
	}

	ast_channel_unlock(chan);

	return 0;
}

int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
{
	return __ast_queue_frame(chan, fin, 0, NULL);
}

int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
{
	return __ast_queue_frame(chan, fin, 1, NULL);
}

/*! \brief Queue a hangup frame for channel */
int ast_queue_hangup(struct ast_channel *chan)
{
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
	int res;

	/* Yeah, let's not change a lock-critical value without locking */
	ast_channel_lock(chan);
	ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
	ast_channel_publish_blob(chan, ast_channel_hangup_request_type(), NULL);

	res = ast_queue_frame(chan, &f);
	ast_channel_unlock(chan);
	return res;
}

/*! \brief Queue a hangup frame for channel */
int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
{
	RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
	int res;

	if (cause >= 0) {
		f.data.uint32 = cause;
	}

	/* Yeah, let's not change a lock-critical value without locking */
	ast_channel_lock(chan);
	ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
	if (cause < 0) {
		f.data.uint32 = ast_channel_hangupcause(chan);
	}
	blob = ast_json_pack("{s: i}",
			     "cause", cause);
	ast_channel_publish_blob(chan, ast_channel_hangup_request_type(), blob);

	res = ast_queue_frame(chan, &f);
	ast_channel_unlock(chan);
	return res;
}

int ast_queue_hold(struct ast_channel *chan, const char *musicclass)
{
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HOLD };
	struct ast_json *blob = NULL;
	int res;

	if (!ast_strlen_zero(musicclass)) {
		f.data.ptr = (void *) musicclass;
		f.datalen = strlen(musicclass) + 1;

		blob = ast_json_pack("{s: s}",
				     "musicclass", musicclass);
	}

	ast_channel_publish_cached_blob(chan, ast_channel_hold_type(), blob);

	res = ast_queue_frame(chan, &f);

	ast_json_unref(blob);

	return res;
}

int ast_queue_unhold(struct ast_channel *chan)
{
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_UNHOLD };
	int res;

	ast_channel_publish_cached_blob(chan, ast_channel_unhold_type(), NULL);

	res = ast_queue_frame(chan, &f);

	return res;
}

/*! \brief Queue a control frame */
int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
{
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
	return ast_queue_frame(chan, &f);
}

/*! \brief Queue a control frame with payload */
int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
			   const void *data, size_t datalen)
{
	struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
	return ast_queue_frame(chan, &f);
}

/*! \brief Set defer DTMF flag on channel */
int ast_channel_defer_dtmf(struct ast_channel *chan)
{
	int pre = 0;

	if (chan) {
		ast_channel_lock(chan);
		pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
		ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
		ast_channel_unlock(chan);
	}
	return pre;
}

/*! \brief Unset defer DTMF flag on channel */
void ast_channel_undefer_dtmf(struct ast_channel *chan)
{
	if (chan) {
		ast_channel_clear_flag(chan, AST_FLAG_DEFER_DTMF);
	}
}

struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
		void *data, int ao2_flags)
{
	return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
}

static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
{
	struct ast_channel *chan = obj;
	const char *name = arg;
	size_t name_len = *(size_t *) data;
	int ret = CMP_MATCH;

	if (ast_strlen_zero(name)) {
		ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
		return CMP_STOP;
	}

	ast_channel_lock(chan);
	if ((!name_len && strcasecmp(ast_channel_name(chan), name))
		|| (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
		ret = 0; /* name match failed, keep looking */
	}
	ast_channel_unlock(chan);

	return ret;
}

static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
{
	struct ast_channel *chan = obj;
	char *context = arg;
	char *exten = data;
	int ret = CMP_MATCH;

	if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
		ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
		return CMP_STOP;
	}

	ast_channel_lock(chan);
	if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
		ret = 0; /* Context match failed, continue */
	} else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
		ret = 0; /* Extension match failed, continue */
	}
	ast_channel_unlock(chan);

	return ret;
}

static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
{
	struct ast_channel *chan = obj;
	char *uniqueid = arg;
	size_t id_len = *(size_t *) data;
	int ret = CMP_MATCH;

	if (ast_strlen_zero(uniqueid)) {
		ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
		return CMP_STOP;
	}

	ast_channel_lock(chan);
	if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
		|| (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
		ret = 0; /* uniqueid match failed, keep looking */
	}
	ast_channel_unlock(chan);

	return ret;
}

struct ast_channel_iterator {
	/* storage for non-dynamically allocated iterator */
	struct ao2_iterator simple_iterator;
	/* pointer to the actual iterator (simple_iterator or a dynamically
	 * allocated iterator)
	 */
	struct ao2_iterator *active_iterator;
};

struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
{
	ao2_iterator_destroy(i->active_iterator);
	ast_free(i);

	return NULL;
}

struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
{
	struct ast_channel_iterator *i;
	char *l_exten = (char *) exten;
	char *l_context = (char *) context;

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

	i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
		l_context, l_exten, OBJ_MULTIPLE);
	if (!i->active_iterator) {
		ast_free(i);
		return NULL;
	}

	return i;
}

struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
{
	struct ast_channel_iterator *i;
	char *l_name = (char *) name;

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

	i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
		l_name, &name_len,
		OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
	if (!i->active_iterator) {
		ast_free(i);
		return NULL;
	}

	return i;
}

struct ast_channel_iterator *ast_channel_iterator_all_new(void)
{
	struct ast_channel_iterator *i;

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

	i->simple_iterator = ao2_iterator_init(channels, 0);
	i->active_iterator = &i->simple_iterator;

	return i;
}

struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
{
	return ao2_iterator_next(i->active_iterator);
}

/* Legacy function, not currently used for lookups, but we need a cmp_fn */
static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
{
	ast_log(LOG_ERROR, "BUG! Should never be called!\n");
	return CMP_STOP;
}

struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
{
	struct ast_channel *chan;
	char *l_name = (char *) name;

	chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
		(name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
	if (chan) {
		return chan;
	}

	if (ast_strlen_zero(l_name)) {
		/* We didn't have a name to search for so quit. */
		return NULL;
	}

	/* Now try a search for uniqueid. */
	return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
}

struct ast_channel *ast_channel_get_by_name(const char *name)
{
	return ast_channel_get_by_name_prefix(name, 0);
}

struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
{
	char *l_exten = (char *) exten;
	char *l_context = (char *) context;

	return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
}

int ast_is_deferrable_frame(const struct ast_frame *frame)
{
	/* Do not add a default entry in this switch statement.  Each new
	 * frame type should be addressed directly as to whether it should
	 * be queued up or not.
	 */
	switch (frame->frametype) {
	case AST_FRAME_BRIDGE_ACTION:
	case AST_FRAME_BRIDGE_ACTION_SYNC:
	case AST_FRAME_CONTROL:
	case AST_FRAME_TEXT:
	case AST_FRAME_IMAGE:
	case AST_FRAME_HTML:
		return 1;

	case AST_FRAME_DTMF_END:
	case AST_FRAME_DTMF_BEGIN:
	case AST_FRAME_VOICE:
	case AST_FRAME_VIDEO:
	case AST_FRAME_NULL:
	case AST_FRAME_IAX:
	case AST_FRAME_CNG:
	case AST_FRAME_MODEM:
	case AST_FRAME_RTCP:
		return 0;
	}
	return 0;
}

/*! \brief Wait, look for hangups and condition arg */
int ast_safe_sleep_conditional(struct ast_channel *chan, int timeout_ms, int (*cond)(void*), void *data)
{
	struct ast_frame *f;
	struct ast_silence_generator *silgen = NULL;
	int res = 0;
	struct timeval start;
	int ms;
	AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;

	AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);

	/* If no other generator is present, start silencegen while waiting */
	if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
		silgen = ast_channel_start_silence_generator(chan);
	}

	start = ast_tvnow();
	while ((ms = ast_remaining_ms(start, timeout_ms))) {
		struct ast_frame *dup_f = NULL;

		if (cond && ((*cond)(data) == 0)) {
			break;
		}
		ms = ast_waitfor(chan, ms);
		if (ms < 0) {
			res = -1;
			break;
		}
		if (ms > 0) {
			f = ast_read(chan);
			if (!f) {
				res = -1;
				break;
			}

			if (!ast_is_deferrable_frame(f)) {
				ast_frfree(f);
				continue;
			}

			if ((dup_f = ast_frisolate(f))) {
				if (dup_f != f) {
					ast_frfree(f);
				}
				AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
			}
		}
	}

	/* stop silgen if present */
	if (silgen) {
		ast_channel_stop_silence_generator(chan, silgen);
	}

	/* We need to free all the deferred frames, but we only need to
	 * queue the deferred frames if there was no error and no
	 * hangup was received
	 */
	ast_channel_lock(chan);
	while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
		if (!res) {
			ast_queue_frame_head(chan, f);
		}
		ast_frfree(f);
	}
	ast_channel_unlock(chan);

	return res;
}

/*! \brief Wait, look for hangups */
int ast_safe_sleep(struct ast_channel *chan, int ms)
{
	return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
}

struct ast_channel *ast_channel_release(struct ast_channel *chan)
{
	/* Safe, even if already unlinked. */
	ao2_unlink(channels, chan);
	return ast_channel_unref(chan);
}

void ast_party_name_init(struct ast_party_name *init)
{
	init->str = NULL;
	init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
	init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
	init->valid = 0;
}

void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
{
	if (dest == src) {
		/* Don't copy to self */
		return;
	}

	ast_free(dest->str);
	dest->str = ast_strdup(src->str);
	dest->char_set = src->char_set;
	dest->presentation = src->presentation;
	dest->valid = src->valid;
}

void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
{
	init->str = NULL;
	init->char_set = guide->char_set;
	init->presentation = guide->presentation;
	init->valid = guide->valid;
}

void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
{
	if (dest == src) {
		/* Don't set to self */
		return;
	}

	if (src->str && src->str != dest->str) {
		ast_free(dest->str);
		dest->str = ast_strdup(src->str);
	}

	dest->char_set = src->char_set;
	dest->presentation = src->presentation;
	dest->valid = src->valid;
}

void ast_party_name_free(struct ast_party_name *doomed)
{
	ast_free(doomed->str);
	doomed->str = NULL;
}

void ast_party_number_init(struct ast_party_number *init)
{
	init->str = NULL;
	init->plan = 0;/* Unknown */
	init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
	init->valid = 0;
}

void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
{
	if (dest == src) {
		/* Don't copy to self */
		return;
	}

	ast_free(dest->str);
	dest->str = ast_strdup(src->str);
	dest->plan = src->plan;
	dest->presentation = src->presentation;
	dest->valid = src->valid;
}

void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
{
	init->str = NULL;
	init->plan = guide->plan;
	init->presentation = guide->presentation;
	init->valid = guide->valid;
}

void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
{
	if (dest == src) {
		/* Don't set to self */
		return;
	}

	if (src->str && src->str != dest->str) {
		ast_free(dest->str);
		dest->str = ast_strdup(src->str);
	}

	dest->plan = src->plan;
	dest->presentation = src->presentation;
	dest->valid = src->valid;
}

void ast_party_number_free(struct ast_party_number *doomed)
{
	ast_free(doomed->str);
	doomed->str = NULL;
}

void ast_party_subaddress_init(struct ast_party_subaddress *init)
{
	init->str = NULL;
	init->type = 0;
	init->odd_even_indicator = 0;
	init->valid = 0;
}

void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
{
	if (dest == src) {
		/* Don't copy to self */
		return;
	}

	ast_free(dest->str);
	dest->str = ast_strdup(src->str);
	dest->type = src->type;
	dest->odd_even_indicator = src->odd_even_indicator;
	dest->valid = src->valid;
}

void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
{
	init->str = NULL;
	init->type = guide->type;
	init->odd_even_indicator = guide->odd_even_indicator;
	init->valid = guide->valid;
}

void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
{
	if (dest == src) {
		/* Don't set to self */
		return;
	}

	if (src->str && src->str != dest->str) {
		ast_free(dest->str);
		dest->str = ast_strdup(src->str);
	}

	dest->type = src->type;
	dest->odd_even_indicator = src->odd_even_indicator;
	dest->valid = src->valid;
}

void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
{
	ast_free(doomed->str);
	doomed->str = NULL;
}

void ast_set_party_id_all(struct ast_set_party_id *update_id)
{
	update_id->name = 1;
	update_id->number = 1;
	update_id->subaddress = 1;
}

void ast_party_id_init(struct ast_party_id *init)
{
	ast_party_name_init(&init->name);
	ast_party_number_init(&init->number);
	ast_party_subaddress_init(&init->subaddress);
	init->tag = NULL;
}

void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
{
	if (dest == src) {
		/* Don't copy to self */
		return;
	}

	ast_party_name_copy(&dest->name, &src->name);
	ast_party_number_copy(&dest->number, &src->number);
	ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);

	ast_free(dest->tag);
	dest->tag = ast_strdup(src->tag);
}

void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
{
	ast_party_name_set_init(&init->name, &guide->name);
	ast_party_number_set_init(&init->number, &guide->number);
	ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
	init->tag = NULL;
}

void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
{
	if (dest == src) {
		/* Don't set to self */
		return;
	}

	if (!update || update->name) {
		ast_party_name_set(&dest->name, &src->name);
	}
	if (!update || update->number) {
		ast_party_number_set(&dest->number, &src->number);
	}
	if (!update || update->subaddress) {
		ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
	}

	if (src->tag && src->tag != dest->tag) {
		ast_free(dest->tag);
		dest->tag = ast_strdup(src->tag);
	}
}

void ast_party_id_free(struct ast_party_id *doomed)
{
	ast_party_name_free(&doomed->name);
	ast_party_number_free(&doomed->number);
	ast_party_subaddress_free(&doomed->subaddress);

	ast_free(doomed->tag);
	doomed->tag = NULL;
}

int ast_party_id_presentation(const struct ast_party_id *id)
{
	int number_priority;
	int number_value;
	int number_screening;
	int name_priority;
	int name_value;

	/* Determine name presentation priority. */
	if (!id->name.valid) {
		name_value = AST_PRES_UNAVAILABLE;
		name_priority = 3;
	} else {
		name_value = id->name.presentation & AST_PRES_RESTRICTION;
		switch (name_value) {
		case AST_PRES_RESTRICTED:
			name_priority = 0;
			break;
		case AST_PRES_ALLOWED:
			name_priority = 1;
			break;
		case AST_PRES_UNAVAILABLE:
			name_priority = 2;
			break;
		default:
			name_value = AST_PRES_UNAVAILABLE;
			name_priority = 3;
			break;
		}
	}

	/* Determine number presentation priority. */
	if (!id->number.valid) {
		number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
		number_value = AST_PRES_UNAVAILABLE;
		number_priority = 3;
	} else {
		number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
		number_value = id->number.presentation & AST_PRES_RESTRICTION;
		switch (number_value) {
		case AST_PRES_RESTRICTED:
			number_priority = 0;
			break;
		case AST_PRES_ALLOWED:
			number_priority = 1;
			break;
		case AST_PRES_UNAVAILABLE:
			number_priority = 2;
			break;
		default:
			number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
			number_value = AST_PRES_UNAVAILABLE;
			number_priority = 3;
			break;
		}
	}

	/* Select the wining presentation value. */
	if (name_priority < number_priority) {
		number_value = name_value;
	}
	if (number_value == AST_PRES_UNAVAILABLE) {
		return AST_PRES_NUMBER_NOT_AVAILABLE;
	}

	return number_value | number_screening;
}

void ast_party_id_invalidate(struct ast_party_id *id)
{
	id->name.valid = 0;
	id->number.valid = 0;
	id->subaddress.valid = 0;
}

void ast_party_id_reset(struct ast_party_id *id)
{
	ast_party_id_free(id);
	ast_party_id_init(id);
}

struct ast_party_id ast_party_id_merge(struct ast_party_id *base, struct ast_party_id *overlay)
{
	struct ast_party_id merged;

	merged = *base;
	if (overlay->name.valid) {
		merged.name = overlay->name;
	}
	if (overlay->number.valid) {
		merged.number = overlay->number;
	}
	if (overlay->subaddress.valid) {
		merged.subaddress = overlay->subaddress;
	}
	/* Note the actual structure is returned and not a pointer to it! */
	return merged;
}

void ast_party_id_merge_copy(struct ast_party_id *dest, struct ast_party_id *base, struct ast_party_id *overlay)
{
	struct ast_party_id merged;

	merged = ast_party_id_merge(base, overlay);
	ast_party_id_copy(dest, &merged);
}

void ast_party_dialed_init(struct ast_party_dialed *init)
{
	init->number.str = NULL;
	init->number.plan = 0;/* Unknown */
	ast_party_subaddress_init(&init->subaddress);
	init->transit_network_select = 0;
}

void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
{
	if (dest == src) {
		/* Don't copy to self */
		return;
	}

	ast_free(dest->number.str);
	dest->number.str = ast_strdup(src->number.str);
	dest->number.plan = src->number.plan;
	ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
	dest->transit_network_select = src->transit_network_select;
}

void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
{
	init->number.str = NULL;
	init->number.plan = guide->number.plan;
	ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
	init->transit_network_select = guide->transit_network_select;
}

void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
{
	if (src->number.str && src->number.str != dest->number.str) {
		ast_free(dest->number.str);
		dest->number.str = ast_strdup(src->number.str);
	}
	dest->number.plan = src->number.plan;

	ast_party_subaddress_set(&dest->subaddress, &src->subaddress);

	dest->transit_network_select = src->transit_network_select;
}

void ast_party_dialed_free(struct ast_party_dialed *doomed)
{
	ast_free(doomed->number.str);
	doomed->number.str = NULL;
	ast_party_subaddress_free(&doomed->subaddress);
}

void ast_party_caller_init(struct ast_party_caller *init)
{
	ast_party_id_init(&init->id);
	ast_party_id_init(&init->ani);
	ast_party_id_init(&init->priv);
	init->ani2 = 0;
}

void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
{
	if (dest == src) {
		/* Don't copy to self */
		return;
	}

	ast_party_id_copy(&dest->id, &src->id);
	ast_party_id_copy(&dest->ani, &src->ani);
	ast_party_id_copy(&dest->priv, &src->priv);
	dest->ani2 = src->ani2;
}

void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
{
	ast_party_id_set_init(&init->id, &guide->id);
	ast_party_id_set_init(&init->ani, &guide->ani);
	ast_party_id_set_init(&init->priv, &guide->priv);
	init->ani2 = guide->ani2;
}

void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
{
	ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
	ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
	ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
	dest->ani2 = src->ani2;
}

void ast_party_caller_free(struct ast_party_caller *doomed)
{
	ast_party_id_free(&doomed->id);
	ast_party_id_free(&doomed->ani);
	ast_party_id_free(&doomed->priv);
}

void ast_party_connected_line_init(struct ast_party_connected_line *init)
{
	ast_party_id_init(&init->id);
	ast_party_id_init(&init->ani);
	ast_party_id_init(&init->priv);
	init->ani2 = 0;
	init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
}

void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
{
	if (dest == src) {
		/* Don't copy to self */
		return;
	}

	ast_party_id_copy(&dest->id, &src->id);
	ast_party_id_copy(&dest->ani, &src->ani);
	ast_party_id_copy(&dest->priv, &src->priv);
	dest->ani2 = src->ani2;
	dest->source = src->source;
}

void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
{
	ast_party_id_set_init(&init->id, &guide->id);
	ast_party_id_set_init(&init->ani, &guide->ani);
	ast_party_id_set_init(&init->priv, &guide->priv);
	init->ani2 = guide->ani2;
	init->source = guide->source;
}

void ast_party_connected_line_set(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src, const struct ast_set_party_connected_line *update)
{
	ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
	ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
	ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
	dest->ani2 = src->ani2;
	dest->source = src->source;
}

void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
{
	connected->id = caller->id;
	connected->ani = caller->ani;
	connected->priv = caller->priv;
	connected->ani2 = caller->ani2;
	connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
}

void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
{
	ast_party_id_free(&doomed->id);
	ast_party_id_free(&doomed->ani);
	ast_party_id_free(&doomed->priv);
}

void ast_party_redirecting_reason_init(struct ast_party_redirecting_reason *init)
{
	init->str = NULL;
	init->code = AST_REDIRECTING_REASON_UNKNOWN;
}

void ast_party_redirecting_reason_copy(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
{
	if (dest == src) {
		return;
	}

	ast_free(dest->str);
	dest->str = ast_strdup(src->str);
	dest->code = src->code;
}

void ast_party_redirecting_reason_set_init(struct ast_party_redirecting_reason *init, const struct ast_party_redirecting_reason *guide)
{
	init->str = NULL;
	init->code = guide->code;
}

void ast_party_redirecting_reason_set(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
{
	if (dest == src) {
		return;
	}

	if (src->str && src->str != dest->str) {
		ast_free(dest->str);
		dest->str = ast_strdup(src->str);
	}

	dest->code = src->code;
}

void ast_party_redirecting_reason_free(struct ast_party_redirecting_reason *doomed)
{
	ast_free(doomed->str);
}


void ast_party_redirecting_init(struct ast_party_redirecting *init)
{
	ast_party_id_init(&init->orig);
	ast_party_id_init(&init->from);
	ast_party_id_init(&init->to);
	ast_party_id_init(&init->priv_orig);
	ast_party_id_init(&init->priv_from);
	ast_party_id_init(&init->priv_to);
	ast_party_redirecting_reason_init(&init->reason);
	ast_party_redirecting_reason_init(&init->orig_reason);
	init->count = 0;
}

void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
{
	if (dest == src) {
		/* Don't copy to self */
		return;
	}

	ast_party_id_copy(&dest->orig, &src->orig);
	ast_party_id_copy(&dest->from, &src->from);
	ast_party_id_copy(&dest->to, &src->to);
	ast_party_id_copy(&dest->priv_orig, &src->priv_orig);
	ast_party_id_copy(&dest->priv_from, &src->priv_from);
	ast_party_id_copy(&dest->priv_to, &src->priv_to);
	ast_party_redirecting_reason_copy(&dest->reason, &src->reason);
	ast_party_redirecting_reason_copy(&dest->orig_reason, &src->orig_reason);
	dest->count = src->count;
}

void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
{
	ast_party_id_set_init(&init->orig, &guide->orig);
	ast_party_id_set_init(&init->from, &guide->from);
	ast_party_id_set_init(&init->to, &guide->to);
	ast_party_id_set_init(&init->priv_orig, &guide->priv_orig);
	ast_party_id_set_init(&init->priv_from, &guide->priv_from);
	ast_party_id_set_init(&init->priv_to, &guide->priv_to);
	ast_party_redirecting_reason_set_init(&init->reason, &guide->reason);
	ast_party_redirecting_reason_set_init(&init->orig_reason, &guide->orig_reason);
	init->count = guide->count;
}

void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
{
	ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
	ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
	ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
	ast_party_id_set(&dest->priv_orig, &src->priv_orig, update ? &update->priv_orig : NULL);
	ast_party_id_set(&dest->priv_from, &src->priv_from, update ? &update->priv_from : NULL);
	ast_party_id_set(&dest->priv_to, &src->priv_to, update ? &update->priv_to : NULL);
	ast_party_redirecting_reason_set(&dest->reason, &src->reason);
	ast_party_redirecting_reason_set(&dest->orig_reason, &src->orig_reason);
	dest->count = src->count;
}

void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
{
	ast_party_id_free(&doomed->orig);
	ast_party_id_free(&doomed->from);
	ast_party_id_free(&doomed->to);
	ast_party_id_free(&doomed->priv_orig);
	ast_party_id_free(&doomed->priv_from);
	ast_party_id_free(&doomed->priv_to);
	ast_party_redirecting_reason_free(&doomed->reason);
	ast_party_redirecting_reason_free(&doomed->orig_reason);
}

/*! \brief Free a channel structure */
static void ast_channel_destructor(void *obj)
{
	struct ast_channel *chan = obj;
	struct ast_var_t *vardata;
	struct ast_frame *f;
	struct varshead *headp;
	struct ast_datastore *datastore;
	char device_name[AST_CHANNEL_NAME];
	ast_callid callid;

	ast_debug(1, "Channel %p '%s' destroying\n", chan, ast_channel_name(chan));

	/* Stop monitoring */
	if (ast_channel_monitor(chan)) {
		ast_channel_monitor(chan)->stop(chan, 0);
	}

	/* If there is native format music-on-hold state, free it */
	if (ast_channel_music_state(chan)) {
		ast_moh_cleanup(chan);
	}

	ast_pbx_hangup_handler_destroy(chan);

	/* Things that may possibly raise Stasis messages shouldn't occur after this point */
	ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEAD);

	if (ast_channel_internal_is_finalized(chan)) {
		/* A channel snapshot should not be in the process of being staged now. */
		ast_assert(!ast_test_flag(ast_channel_flags(chan), AST_FLAG_SNAPSHOT_STAGE));

		ast_channel_lock(chan);
		ast_channel_publish_snapshot(chan);
		ast_channel_unlock(chan);
		publish_cache_clear(chan);
	}

	ast_channel_lock(chan);

	/* Get rid of each of the data stores on the channel */
	while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
		/* Free the data store */
		ast_datastore_free(datastore);

	/* While the channel is locked, take the reference to its callid while we tear down the call. */
	callid = ast_channel_callid(chan);
	ast_channel_callid_cleanup(chan);

	ast_channel_unlock(chan);

	/* Lock and unlock the channel just to be sure nobody has it locked still
	   due to a reference that was stored in a datastore. (i.e. app_chanspy) */
	ast_channel_lock(chan);
	ast_channel_unlock(chan);

	if (ast_channel_tech_pvt(chan)) {
		ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
		ast_free(ast_channel_tech_pvt(chan));
	}

	if (ast_channel_sched(chan)) {
		ast_sched_context_destroy(ast_channel_sched(chan));
	}

	if (ast_channel_internal_is_finalized(chan)) {
		char *dashptr;

		ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
		if ((dashptr = strrchr(device_name, '-'))) {
			*dashptr = '\0';
		}
	} else {
		device_name[0] = '\0';
	}

	/* Free translators */
	if (ast_channel_readtrans(chan))
		ast_translator_free_path(ast_channel_readtrans(chan));
	if (ast_channel_writetrans(chan))
		ast_translator_free_path(ast_channel_writetrans(chan));
	if (ast_channel_pbx(chan))
		ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));

	/* Free formats */
	ast_channel_set_oldwriteformat(chan, NULL);
	ast_channel_set_rawreadformat(chan, NULL);
	ast_channel_set_rawwriteformat(chan, NULL);
	ast_channel_set_readformat(chan, NULL);
	ast_channel_set_writeformat(chan, NULL);

	ast_party_dialed_free(ast_channel_dialed(chan));
	ast_party_caller_free(ast_channel_caller(chan));
	ast_party_connected_line_free(ast_channel_connected(chan));
	ast_party_connected_line_free(ast_channel_connected_indicated(chan));
	ast_party_redirecting_free(ast_channel_redirecting(chan));

	/* Close pipes if appropriate */
	ast_channel_internal_alertpipe_close(chan);
	if (ast_channel_timer(chan)) {
		ast_timer_close(ast_channel_timer(chan));
		ast_channel_timer_set(chan, NULL);
	}
	while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
		ast_frfree(f);

	/* loop over the variables list, freeing all data and deleting list items */
	/* no need to lock the list, as the channel is already locked */
	headp = ast_channel_varshead(chan);
	while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
		ast_var_delete(vardata);

	ast_app_group_discard(chan);

	/* Destroy the jitterbuffer */
	ast_jb_destroy(chan);

	if (ast_channel_cdr(chan)) {
		ast_cdr_free(ast_channel_cdr(chan));
		ast_channel_cdr_set(chan, NULL);
	}

	if (ast_channel_zone(chan)) {
		ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
	}

	ast_channel_internal_cleanup(chan);

	if (device_name[0]) {
		/*
		 * We have a device name to notify of a new state.
		 *
		 * Queue an unknown state, because, while we know that this particular
		 * instance is dead, we don't know the state of all other possible
		 * instances.
		 */
		ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, (ast_test_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_DEVSTATE_CACHE) ? AST_DEVSTATE_NOT_CACHABLE : AST_DEVSTATE_CACHABLE), device_name);
	}

	ast_channel_nativeformats_set(chan, NULL);

	ast_channel_named_callgroups_set(chan, NULL);
	ast_channel_named_pickupgroups_set(chan, NULL);

	ast_atomic_fetchadd_int(&chancount, -1);
}

/*! \brief Free a dummy channel structure */
static void ast_dummy_channel_destructor(void *obj)
{
	struct ast_channel *chan = obj;
	struct ast_datastore *datastore;
	struct ast_var_t *vardata;
	struct varshead *headp;

	ast_pbx_hangup_handler_destroy(chan);

	/* Get rid of each of the data stores on the channel */
	while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry))) {
		/* Free the data store */
		ast_datastore_free(datastore);
	}

	ast_party_dialed_free(ast_channel_dialed(chan));
	ast_party_caller_free(ast_channel_caller(chan));
	ast_party_connected_line_free(ast_channel_connected(chan));
	ast_party_connected_line_free(ast_channel_connected_indicated(chan));
	ast_party_redirecting_free(ast_channel_redirecting(chan));

	/* loop over the variables list, freeing all data and deleting list items */
	/* no need to lock the list, as the channel is already locked */
	headp = ast_channel_varshead(chan);
	while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
		ast_var_delete(vardata);

	if (ast_channel_cdr(chan)) {
		ast_cdr_free(ast_channel_cdr(chan));
		ast_channel_cdr_set(chan, NULL);
	}

	ast_channel_internal_cleanup(chan);
}

struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
{
	return ast_datastore_alloc(info, uid);
}

int ast_channel_datastore_free(struct ast_datastore *datastore)
{
	return ast_datastore_free(datastore);
}

int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
{
	struct ast_datastore *datastore = NULL, *datastore2;

	AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
		if (datastore->inheritance > 0) {
			datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
			if (datastore2) {
				datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
				datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
				AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
			}
		}
	}
	return 0;
}

int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
{
	int res = 0;

	AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);

	return res;
}

int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
{
	return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
}

struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
{
	struct ast_datastore *datastore = NULL;

	if (info == NULL)
		return NULL;

	AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
		if (datastore->info != info) {
			continue;
		}

		if (uid == NULL) {
			/* matched by type only */
			break;
		}

		if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
			/* Matched by type AND uid */
			break;
		}
	}

	return datastore;
}

/*! Set the file descriptor on the channel */
void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
{
	ast_channel_internal_fd_set(chan, which, fd);
	return;
}

void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
{
	ast_channel_lock(chan);

	ast_channel_softhangup_internal_flag_clear(chan, flag);

	if (!ast_channel_softhangup_internal_flag(chan)) {
		struct ast_frame *fr;

		/* If we have completely cleared the softhangup flag,
		 * then we need to fully abort the hangup process.  This requires
		 * pulling the END_OF_Q frame out of the channel frame queue if it
		 * still happens to be there. */

		fr = AST_LIST_LAST(ast_channel_readq(chan));
		if (fr && fr->frametype == AST_FRAME_CONTROL &&
				fr->subclass.integer == AST_CONTROL_END_OF_Q) {
			AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
			ast_frfree(fr);
		}
	}

	ast_channel_unlock(chan);
}

/*! \brief Softly hangup a channel, don't lock */
int ast_softhangup_nolock(struct ast_channel *chan, int cause)
{
	ast_debug(1, "Soft-Hanging (%#04x) up channel '%s'\n", (unsigned)cause, ast_channel_name(chan));
	/* Inform channel driver that we need to be hung up, if it cares */
	ast_channel_softhangup_internal_flag_add(chan, cause);
	ast_queue_frame(chan, &ast_null_frame);
	/* Interrupt any poll call or such */
	if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
		pthread_kill(ast_channel_blocker(chan), SIGURG);
	return 0;
}

/*! \brief Softly hangup a channel, lock */
int ast_softhangup(struct ast_channel *chan, int cause)
{
	RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
	int res;

	ast_channel_lock(chan);
	res = ast_softhangup_nolock(chan, cause);
	blob = ast_json_pack("{s: i, s: b}",
			     "cause", cause,
			     "soft", 1);
	ast_channel_publish_blob(chan, ast_channel_hangup_request_type(), blob);
	ast_channel_unlock(chan);

	return res;
}

static void free_translation(struct ast_channel *clonechan)
{
	if (ast_channel_writetrans(clonechan)) {
		ast_translator_free_path(ast_channel_writetrans(clonechan));
	}
	if (ast_channel_readtrans(clonechan)) {
		ast_translator_free_path(ast_channel_readtrans(clonechan));
	}
	ast_channel_writetrans_set(clonechan, NULL);
	ast_channel_readtrans_set(clonechan, NULL);
}

void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
{
	RAII_VAR(struct ast_channel *, bridge, ast_channel_bridge_peer(chan), ast_channel_cleanup);

	ast_channel_lock(chan);
	if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
		ast_channel_hangupsource_set(chan, source);
	}
	ast_channel_unlock(chan);

	if (bridge) {
		ast_channel_lock(bridge);
		if (force || ast_strlen_zero(ast_channel_hangupsource(bridge))) {
			ast_channel_hangupsource_set(bridge, source);
		}
		ast_channel_unlock(bridge);
	}
}

int ast_channel_has_audio_frame_or_monitor(struct ast_channel *chan)
{
	return ast_channel_monitor(chan)
		|| !ast_audiohook_write_list_empty(ast_channel_audiohooks(chan))
		|| !ast_framehook_list_contains_no_active(ast_channel_framehooks(chan));
}

int ast_channel_has_hook_requiring_audio(struct ast_channel *chan)
{
	return ast_channel_monitor(chan)
		|| !ast_audiohook_write_list_empty(ast_channel_audiohooks(chan))
		|| !ast_framehook_list_contains_no_active_of_type(ast_channel_framehooks(chan), AST_FRAME_VOICE);
}

static void destroy_hooks(struct ast_channel *chan)
{
	if (ast_channel_audiohooks(chan)) {
		ast_audiohook_detach_list(ast_channel_audiohooks(chan));
		ast_channel_audiohooks_set(chan, NULL);
	}

	ast_framehook_list_destroy(chan);
}

/*! \brief Hangup a channel */
void ast_hangup(struct ast_channel *chan)
{
	/* Be NULL safe for RAII_VAR() usage. */
	if (!chan) {
		return;
	}

	ast_debug(1, "Channel %p '%s' hanging up.  Refs: %d\n", chan, ast_channel_name(chan),
		ao2_ref(chan, 0));

	ast_autoservice_stop(chan);

	ast_channel_lock(chan);

	while (ast_channel_masq(chan) || ast_channel_masqr(chan))  {
		CHANNEL_DEADLOCK_AVOIDANCE(chan);
	}

	/* Mark as a zombie so a masquerade cannot be setup on this channel. */
	ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);

	ast_channel_unlock(chan);

	/*
	 * XXX if running the hangup handlers here causes problems
	 * because the handlers take too long to execute, we could move
	 * the meat of this function into another thread.  A thread
	 * where channels go to die.
	 *
	 * If this is done, ast_autoservice_chan_hangup_peer() will no
	 * longer be needed.
	 */
	ast_pbx_hangup_handler_run(chan);
	ao2_unlink(channels, chan);
	ast_channel_lock(chan);

	destroy_hooks(chan);

	free_translation(chan);
	/* Close audio stream */
	if (ast_channel_stream(chan)) {
		ast_closestream(ast_channel_stream(chan));
		ast_channel_stream_set(chan, NULL);
	}
	/* Close video stream */
	if (ast_channel_vstream(chan)) {
		ast_closestream(ast_channel_vstream(chan));
		ast_channel_vstream_set(chan, NULL);
	}
	if (ast_channel_sched(chan)) {
		ast_sched_context_destroy(ast_channel_sched(chan));
		ast_channel_sched_set(chan, NULL);
	}

	if (ast_channel_generatordata(chan)) {	/* Clear any tone stuff remaining */
		if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
			ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
		}
	}
	ast_channel_generatordata_set(chan, NULL);
	ast_channel_generator_set(chan, NULL);

	if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
		ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
			"is blocked by thread %ld in procedure %s!  Expect a failure\n",
			(long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
		ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
	}

	if (ast_channel_tech(chan)->hangup) {
		ast_channel_tech(chan)->hangup(chan);
	}

	ast_channel_unlock(chan);

	ast_cc_offer(chan);

	ast_channel_unref(chan);
}

/*!
 * \internal
 * \brief Set channel answered time if not already set.
 * \since 13.11.0
 *
 * \param chan Channel to set answered time.
 *
 * \return Nothing
 */
static void set_channel_answer_time(struct ast_channel *chan)
{
	if (ast_tvzero(ast_channel_answertime(chan))) {
		struct timeval answertime;

		answertime = ast_tvnow();
		ast_channel_answertime_set(chan, &answertime);
	}
}

int ast_raw_answer(struct ast_channel *chan)
{
	int res = 0;

	ast_channel_lock(chan);

	/* You can't answer an outbound call */
	if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
		ast_channel_unlock(chan);
		return 0;
	}

	/* Stop if we're a zombie or need a soft hangup */
	if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
		ast_channel_unlock(chan);
		return -1;
	}

	/*
	 * Mark when incoming channel answered so we can know how
	 * long the channel has been up.
	 */
	set_channel_answer_time(chan);

	ast_channel_unlock(chan);

	switch (ast_channel_state(chan)) {
	case AST_STATE_RINGING:
	case AST_STATE_RING:
		ast_channel_lock(chan);
		if (ast_channel_tech(chan)->answer) {
			res = ast_channel_tech(chan)->answer(chan);
		}
		ast_setstate(chan, AST_STATE_UP);
		ast_channel_unlock(chan);
		break;
	case AST_STATE_UP:
		break;
	default:
		break;
	}

	ast_indicate(chan, -1);

	return res;
}

int __ast_answer(struct ast_channel *chan, unsigned int delay)
{
	int res = 0;
	enum ast_channel_state old_state;

	old_state = ast_channel_state(chan);
	if ((res = ast_raw_answer(chan))) {
		return res;
	}

	switch (old_state) {
	case AST_STATE_RINGING:
	case AST_STATE_RING:
		/* wait for media to start flowing, but don't wait any longer
		 * than 'delay' or 500 milliseconds, whichever is longer
		 */
		do {
			AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
			struct ast_frame *cur;
			struct ast_frame *new_frame;
			int timeout_ms = MAX(delay, 500);
			unsigned int done = 0;
			struct timeval start;

			AST_LIST_HEAD_INIT_NOLOCK(&frames);

			start = ast_tvnow();
			for (;;) {
				int ms = ast_remaining_ms(start, timeout_ms);
				ms = ast_waitfor(chan, ms);
				if (ms < 0) {
					ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
					res = -1;
					break;
				}
				if (ms == 0) {
					ast_debug(2, "Didn't receive a media frame from %s within %u ms of answering. Continuing anyway\n", ast_channel_name(chan), MAX(delay, 500));
					break;
				}
				cur = ast_read(chan);
				if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
					     (cur->subclass.integer == AST_CONTROL_HANGUP))) {
					if (cur) {
						ast_frfree(cur);
					}
					res = -1;
					ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
					break;
				}

				if ((new_frame = ast_frisolate(cur)) != cur) {
					ast_frfree(cur);
				}

				AST_LIST_INSERT_HEAD(&frames, new_frame, frame_list);

				/* if a specific delay period was requested, continue
				 * until that delay has passed. don't stop just because
				 * incoming media has arrived.
				 */
				if (delay) {
					continue;
				}

				switch (new_frame->frametype) {
					/* all of these frametypes qualify as 'media' */
				case AST_FRAME_VOICE:
				case AST_FRAME_VIDEO:
				case AST_FRAME_TEXT:
				case AST_FRAME_DTMF_BEGIN:
				case AST_FRAME_DTMF_END:
				case AST_FRAME_IMAGE:
				case AST_FRAME_HTML:
				case AST_FRAME_MODEM:
				case AST_FRAME_RTCP:
					done = 1;
					break;
				case AST_FRAME_CONTROL:
				case AST_FRAME_IAX:
				case AST_FRAME_BRIDGE_ACTION:
				case AST_FRAME_BRIDGE_ACTION_SYNC:
				case AST_FRAME_NULL:
				case AST_FRAME_CNG:
					break;
				}

				if (done) {
					break;
				}
			}

			ast_channel_lock(chan);
			while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
				if (res == 0) {
					ast_queue_frame_head(chan, cur);
				}
				ast_frfree(cur);
			}
			ast_channel_unlock(chan);
		} while (0);
		break;
	default:
		break;
	}

	return res;
}

int ast_answer(struct ast_channel *chan)
{
	return __ast_answer(chan, 0);
}

inline int ast_auto_answer(struct ast_channel *chan)
{
	if (ast_channel_state(chan) == AST_STATE_UP) {
		/* Already answered */
		return 0;
	}
	return ast_answer(chan);
}

int ast_channel_get_duration(struct ast_channel *chan)
{
	ast_assert(NULL != chan);

	if (ast_tvzero(ast_channel_creationtime(chan))) {
		return 0;
	}
	return (ast_tvdiff_ms(ast_tvnow(), ast_channel_creationtime(chan)) / 1000);
}

int ast_channel_get_up_time(struct ast_channel *chan)
{
	ast_assert(NULL != chan);

	if (ast_tvzero(ast_channel_answertime(chan))) {
		return 0;
	}
	return (ast_tvdiff_ms(ast_tvnow(), ast_channel_answertime(chan)) / 1000);
}

static void deactivate_generator_nolock(struct ast_channel *chan)
{
	if (ast_channel_generatordata(chan)) {
		struct ast_generator *generator = ast_channel_generator(chan);

		if (generator && generator->release) {
			generator->release(chan, ast_channel_generatordata(chan));
		}
		ast_channel_generatordata_set(chan, NULL);
		ast_channel_generator_set(chan, NULL);
		ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
		ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
		ast_settimeout(chan, 0, NULL, NULL);
	}
}

void ast_deactivate_generator(struct ast_channel *chan)
{
	ast_channel_lock(chan);
	deactivate_generator_nolock(chan);
	ast_channel_unlock(chan);
}

static void generator_write_format_change(struct ast_channel *chan)
{
	struct ast_generator *generator;

	ast_channel_lock(chan);
	generator = ast_channel_generator(chan);
	if (generator && generator->write_format_change) {
		generator->write_format_change(chan, ast_channel_generatordata(chan));
	}
	ast_channel_unlock(chan);
}

static int generator_force(const void *data)
{
	/* Called if generator doesn't have data */
	void *tmp;
	int res;
	int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
	struct ast_channel *chan = (struct ast_channel *)data;

	ast_channel_lock(chan);
	tmp = ast_channel_generatordata(chan);
	ast_channel_generatordata_set(chan, NULL);
	if (ast_channel_generator(chan))
		generate = ast_channel_generator(chan)->generate;
	ast_channel_unlock(chan);

	if (!tmp || !generate) {
		return 0;
	}

	res = generate(chan, tmp, 0, ast_format_get_sample_rate(ast_channel_writeformat(chan)) / 50);

	ast_channel_lock(chan);
	if (ast_channel_generator(chan) && generate == ast_channel_generator(chan)->generate) {
		ast_channel_generatordata_set(chan, tmp);
	}
	ast_channel_unlock(chan);

	if (res) {
		ast_debug(1, "Auto-deactivating generator\n");
		ast_deactivate_generator(chan);
	}

	return 0;
}

int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
{
	int res = 0;
	void *generatordata = NULL;

	ast_channel_lock(chan);
	if (ast_channel_generatordata(chan)) {
		struct ast_generator *generator_old = ast_channel_generator(chan);

		if (generator_old && generator_old->release) {
			generator_old->release(chan, ast_channel_generatordata(chan));
		}
	}
	if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
		res = -1;
	}
	ast_channel_generatordata_set(chan, generatordata);
	if (!res) {
		ast_settimeout(chan, 50, generator_force, chan);
		ast_channel_generator_set(chan, gen);
	}
	ast_channel_unlock(chan);

	ast_prod(chan);

	return res;
}

/*! \brief Wait for x amount of time on a file descriptor to have input.  */
int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
{
	int winner = -1;
	ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
	return winner;
}

/*! \brief Wait for x amount of time on a file descriptor to have input.  */
struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
					int *exception, int *outfd, int *ms)
{
	struct timeval start = { 0 , 0 };
	struct pollfd *pfds = NULL;
	int res;
	long rms;
	int x, y, max;
	int sz = nfds;
	struct timeval now = { 0, 0 };
	struct timeval whentohangup = { 0, 0 }, diff;
	struct ast_channel *winner = NULL;
	struct fdmap {
		int chan;
		int fdno;
	} *fdmap = NULL;

	if (outfd) {
		*outfd = -99999;
	}
	if (exception) {
		*exception = 0;
	}

	for (x = 0; x < n; x++) {
		ast_channel_lock(c[x]);
		if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
			if (ast_tvzero(whentohangup))
				now = ast_tvnow();
			diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
			if (diff.tv_sec < 0 || ast_tvzero(diff)) {
				ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
				/* Should already be hungup */
				ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
				ast_channel_unlock(c[x]);
				return c[x];
			}
			if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
				whentohangup = diff;
		}
		sz += ast_channel_fd_count(c[x]);
		ast_channel_unlock(c[x]);
	}

	if (!sz) {
		return NULL;
	}

	pfds = ast_alloca(sizeof(*pfds) * sz);
	fdmap = ast_alloca(sizeof(*fdmap) * sz);

	/* Wait full interval */
	rms = *ms;
	/* INT_MAX, not LONG_MAX, because it matters on 64-bit */
	if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
		rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
		if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
			rms =  *ms;
		}
	} else if (!ast_tvzero(whentohangup) && rms < 0) {
		/* Tiny corner case... call would need to last >24 days */
		rms = INT_MAX;
	}
	/*
	 * Build the pollfd array, putting the channels' fds first,
	 * followed by individual fds. Order is important because
	 * individual fd's must have priority over channel fds.
	 */
	max = 0;
	for (x = 0; x < n; x++) {
		ast_channel_lock(c[x]);
		for (y = 0; y < ast_channel_fd_count(c[x]); y++) {
			fdmap[max].fdno = y;  /* fd y is linked to this pfds */
			fdmap[max].chan = x;  /* channel x is linked to this pfds */
			max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
		}
		CHECK_BLOCKING(c[x]);
		ast_channel_unlock(c[x]);
	}
	/* Add the individual fds */
	for (x = 0; x < nfds; x++) {
		fdmap[max].chan = -1;
		max += ast_add_fd(&pfds[max], fds[x]);
	}

	if (*ms > 0) {
		start = ast_tvnow();
	}

	if (sizeof(int) == 4) {	/* XXX fix timeout > 600000 on linux x86-32 */
		do {
			int kbrms = rms;
			if (kbrms > 600000) {
				kbrms = 600000;
			}
			res = ast_poll(pfds, max, kbrms);
			if (!res) {
				rms -= kbrms;
			}
		} while (!res && (rms > 0));
	} else {
		res = ast_poll(pfds, max, rms);
	}
	for (x = 0; x < n; x++) {
		ast_channel_lock(c[x]);
		ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
		ast_channel_unlock(c[x]);
	}
	if (res < 0) { /* Simulate a timeout if we were interrupted */
		if (errno != EINTR) {
			*ms = -1;
		}
		return NULL;
	}
	if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
		now = ast_tvnow();
		for (x = 0; x < n; x++) {
			if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
				ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
				ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
				if (winner == NULL) {
					winner = c[x];
				}
			}
		}
	}
	if (res == 0) { /* no fd ready, reset timeout and done */
		*ms = 0;	/* XXX use 0 since we may not have an exact timeout. */
		return winner;
	}
	/*
	 * Then check if any channel or fd has a pending event.
	 * Remember to check channels first and fds last, as they
	 * must have priority on setting 'winner'
	 */
	for (x = 0; x < max; x++) {
		res = pfds[x].revents;
		if (res == 0) {
			continue;
		}
		if (fdmap[x].chan >= 0) {	/* this is a channel */
			winner = c[fdmap[x].chan];	/* override previous winners */
			ast_channel_lock(winner);
			if (res & POLLPRI) {
				ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
			} else {
				ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
			}
			ast_channel_fdno_set(winner, fdmap[x].fdno);
			ast_channel_unlock(winner);
		} else {			/* this is an fd */
			if (outfd) {
				*outfd = pfds[x].fd;
			}
			if (exception) {
				*exception = (res & POLLPRI) ? -1 : 0;
			}
			winner = NULL;
		}
	}
	if (*ms > 0) {
		*ms -= ast_tvdiff_ms(ast_tvnow(), start);
		if (*ms < 0) {
			*ms = 0;
		}
	}
	return winner;
}

struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
{
	return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
}

int ast_waitfor(struct ast_channel *c, int ms)
{
	if (ms < 0) {
		do {
			ms = 100000;
			ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
		} while (!ms);
	} else {
		ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
	}
	return ms;
}

int ast_waitfordigit(struct ast_channel *c, int ms)
{
	return ast_waitfordigit_full(c, ms, NULL, -1, -1);
}

int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
{
	return ast_settimeout_full(c, rate, func, data, 0);
}

int ast_settimeout_full(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data, unsigned int is_ao2_obj)
{
	int res;
	unsigned int real_rate = rate, max_rate;

	ast_channel_lock(c);

	if (ast_channel_timingfd(c) == -1) {
		ast_channel_unlock(c);
		return -1;
	}

	if (!func) {
		rate = 0;
		data = NULL;
	}

	if (rate && rate > (max_rate = ast_timer_get_max_rate(ast_channel_timer(c)))) {
		real_rate = max_rate;
	}

	ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);

	res = ast_timer_set_rate(ast_channel_timer(c), real_rate);

	if (ast_channel_timingdata(c) && ast_test_flag(ast_channel_flags(c), AST_FLAG_TIMINGDATA_IS_AO2_OBJ)) {
		ao2_ref(ast_channel_timingdata(c), -1);
	}

	ast_channel_timingfunc_set(c, func);
	ast_channel_timingdata_set(c, data);

	if (data && is_ao2_obj) {
		ao2_ref(data, 1);
		ast_set_flag(ast_channel_flags(c), AST_FLAG_TIMINGDATA_IS_AO2_OBJ);
	} else {
		ast_clear_flag(ast_channel_flags(c), AST_FLAG_TIMINGDATA_IS_AO2_OBJ);
	}

	if (func == NULL && rate == 0 && ast_channel_fdno(c) == AST_TIMING_FD) {
		/* Clearing the timing func and setting the rate to 0
		 * means that we don't want to be reading from the timingfd
		 * any more. Setting c->fdno to -1 means we won't have any
		 * errant reads from the timingfd, meaning we won't potentially
		 * miss any important frames.
		 */
		ast_channel_fdno_set(c, -1);
	}

	ast_channel_unlock(c);

	return res;
}

int ast_waitfordigit_full(struct ast_channel *c, int timeout_ms, const char *breakon, int audiofd, int cmdfd)
{
	struct timeval start = ast_tvnow();
	int ms;

	/* Stop if we're a zombie or need a soft hangup */
	if (ast_test_flag(ast_channel_flags(c), AST_FLAG_ZOMBIE) || ast_check_hangup(c))
		return -1;

	/* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
	ast_channel_set_flag(c, AST_FLAG_END_DTMF_ONLY);

	/* Wait for a digit, no more than timeout_ms milliseconds total.
	 * Or, wait indefinitely if timeout_ms is <0.
	 */
	while ((ms = ast_remaining_ms(start, timeout_ms))) {
		struct ast_channel *rchan;
		int outfd = -1;

		errno = 0;
		/* While ast_waitfor_nandfds tries to help by reducing the timeout by how much was waited,
		 * it is unhelpful if it waited less than a millisecond.
		 */
		rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);

		if (!rchan && outfd < 0 && ms) {
			if (errno == 0 || errno == EINTR)
				continue;
			ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
			ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
			return -1;
		} else if (outfd > -1) {
			/* The FD we were watching has something waiting */
			ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
			ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
			return 1;
		} else if (rchan) {
			int res;
			struct ast_frame *f = ast_read(c);

			if (!f) {
				ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);

				return -1;
			}

			switch (f->frametype) {
			case AST_FRAME_DTMF_BEGIN:
				break;
			case AST_FRAME_DTMF_END:
				res = f->subclass.integer;
				if (!breakon || strchr(breakon, res)) {
					ast_frfree(f);
					ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
					return res;
				}
				break;
			case AST_FRAME_CONTROL:
				switch (f->subclass.integer) {
				case AST_CONTROL_HANGUP:
					ast_frfree(f);
					ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
					return -1;
				case AST_CONTROL_STREAM_STOP:
				case AST_CONTROL_STREAM_SUSPEND:
				case AST_CONTROL_STREAM_RESTART:
				case AST_CONTROL_STREAM_REVERSE:
				case AST_CONTROL_STREAM_FORWARD:
					/* Fall-through and treat as if it were a DTMF signal. Items
					 * that perform stream control will handle this. */
					res = f->subclass.integer;
					ast_frfree(f);
					ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
					return res;
				case AST_CONTROL_PVT_CAUSE_CODE:
				case AST_CONTROL_RINGING:
				case AST_CONTROL_ANSWER:
				case AST_CONTROL_SRCUPDATE:
				case AST_CONTROL_SRCCHANGE:
				case AST_CONTROL_CONNECTED_LINE:
				case AST_CONTROL_REDIRECTING:
				case AST_CONTROL_UPDATE_RTP_PEER:
				case AST_CONTROL_HOLD:
				case AST_CONTROL_UNHOLD:
				case -1:
					/* Unimportant */
					break;
				default:
					ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
					break;
				}
				break;
			case AST_FRAME_VOICE:
				/* Write audio if appropriate */
				if (audiofd > -1) {
					if (write(audiofd, f->data.ptr, f->datalen) < 0) {
						ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
					}
				}
			default:
				/* Ignore */
				break;
			}
			ast_frfree(f);
		}
	}

	ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);

	return 0; /* Time is up */
}

enum DtmfDirection {
	DTMF_RECEIVED,
	DTMF_SENT
};

static const char *dtmf_direction_to_string(enum DtmfDirection direction)
{
	switch (direction) {
	case DTMF_RECEIVED:
		return "Received";
	case DTMF_SENT:
		return "Sent";
	}

	return "?";
}

static void send_dtmf_begin_event(struct ast_channel *chan,
	enum DtmfDirection direction, const char digit)
{
	RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
	char digit_str[] = { digit, '\0' };

	blob = ast_json_pack("{ s: s, s: s }",
		"digit", digit_str,
		"direction", dtmf_direction_to_string(direction));
	if (!blob) {
		return;
	}

	ast_channel_publish_cached_blob(chan, ast_channel_dtmf_begin_type(), blob);
}

static void send_dtmf_end_event(struct ast_channel *chan,
	enum DtmfDirection direction, const char digit, long duration_ms)
{
	RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
	char digit_str[] = { digit, '\0' };

	blob = ast_json_pack("{ s: s, s: s, s: i }",
		"digit", digit_str,
		"direction", dtmf_direction_to_string(direction),
		"duration_ms", duration_ms);
	if (!blob) {
		return;
	}

	ast_channel_publish_cached_blob(chan, ast_channel_dtmf_end_type(), blob);
}

static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
{
	struct ast_generator *generator;
	void *gendata;
	int res;
	int samples;

	generator = ast_channel_generator(chan);
	if (!generator
		|| !generator->generate
		|| f->frametype != AST_FRAME_VOICE
		|| !ast_channel_generatordata(chan)
		|| ast_channel_timingfunc(chan)) {
		return;
	}

	/*
	 * We must generate frames in phase locked mode since
	 * we have no internal timer available.
	 */
	if (ast_format_cmp(f->subclass.format, ast_channel_writeformat(chan)) == AST_FORMAT_CMP_NOT_EQUAL) {
		float factor;
		factor = ((float) ast_format_get_sample_rate(ast_channel_writeformat(chan))) / ((float) ast_format_get_sample_rate(f->subclass.format));
		samples = (int) (((float) f->samples) * factor);
	} else {
		samples = f->samples;
	}

	gendata = ast_channel_generatordata(chan);
	ast_channel_generatordata_set(chan, NULL);     /* reset, to let writes go through */

	/*
	 * This unlock is here based on two assumptions that hold true at
	 * this point in the code. 1) this function is only called from
	 * within __ast_read() and 2) all generators call ast_write() in
	 * their generate callback.
	 *
	 * The reason this is added is so that when ast_write is called,
	 * the lock that occurs there will not recursively lock the
	 * channel.  Doing this will allow deadlock avoidance to work in
	 * deeper functions.
	 */
	ast_channel_unlock(chan);
	res = generator->generate(chan, gendata, f->datalen, samples);
	ast_channel_lock(chan);
	if (generator == ast_channel_generator(chan)) {
		ast_channel_generatordata_set(chan, gendata);
		if (res) {
			ast_debug(1, "Auto-deactivating generator\n");
			ast_deactivate_generator(chan);
		}
	}
}

static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
{
	struct ast_frame *fr = ast_channel_dtmff(chan);

	fr->frametype = AST_FRAME_DTMF_END;
	fr->subclass.integer = f->subclass.integer;
	fr->len = f->len;

	/* The only time this function will be called is for a frame that just came
	 * out of the channel driver.  So, we want to stick it on the tail of the
	 * readq. */

	ast_queue_frame(chan, fr);
}

/*!
 * \brief Determine whether or not we should ignore DTMF in the readq
 */
static inline int should_skip_dtmf(struct ast_channel *chan)
{
	if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
		/* We're in the middle of emulating a digit, or DTMF has been
		 * explicitly deferred.  Skip this digit, then. */
		return 1;
	}

	if (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
			ast_tvdiff_ms(ast_tvnow(), *ast_channel_dtmf_tv(chan)) < AST_MIN_DTMF_GAP) {
		/* We're not in the middle of a digit, but it hasn't been long enough
		 * since the last digit, so we'll have to skip DTMF for now. */
		return 1;
	}

	return 0;
}

/*!
 * \brief calculates the number of samples to jump forward with in a monitor stream.

 * \note When using ast_seekstream() with the read and write streams of a monitor,
 * the number of samples to seek forward must be of the same sample rate as the stream
 * or else the jump will not be calculated correctly.
 *
 * \retval number of samples to seek forward after rate conversion.
 */
static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
{
	int diff = sample_rate - seek_rate;

	if (diff > 0) {
		samples = samples / (float) (sample_rate / seek_rate);
	} else if (diff < 0) {
		samples = samples * (float) (seek_rate / sample_rate);
	}

	return samples;
}

static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio, int dropnondefault)
{
	struct ast_frame *f = NULL;	/* the return value */
	int prestate;
	int cause = 0;
	struct ast_stream *stream = NULL, *default_stream = NULL;

	/* this function is very long so make sure there is only one return
	 * point at the end (there are only two exceptions to this).
	 */
	ast_channel_lock(chan);

	/* Stop if we're a zombie or need a soft hangup */
	if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
		if (ast_channel_generator(chan))
			ast_deactivate_generator(chan);

		/*
		 * It is possible for chan->_softhangup to be set and there
		 * still be control frames that need to be read.  Instead of
		 * just going to 'done' in the case of ast_check_hangup(), we
		 * need to queue the end-of-Q frame so that it can mark the end
		 * of the read queue.  If there are frames to be read,
		 * ast_queue_control() will be called repeatedly, but will only
		 * queue the first end-of-Q frame.
		 */
		if (ast_channel_softhangup_internal_flag(chan)) {
			ast_queue_control(chan, AST_CONTROL_END_OF_Q);
		} else {
			goto done;
		}
	} else {
#ifdef AST_DEVMODE
		/*
		 * The ast_waitfor() code records which of the channel's file
		 * descriptors reported that data is available.  In theory,
		 * ast_read() should only be called after ast_waitfor() reports
		 * that a channel has data available for reading.  However,
		 * there still may be some edge cases throughout the code where
		 * ast_read() is called improperly.  This can potentially cause
		 * problems, so if this is a developer build, make a lot of
		 * noise if this happens so that it can be addressed.
		 *
		 * One of the potential problems is blocking on a dead channel.
		 */
		if (ast_channel_fdno(chan) == -1) {
			ast_log(LOG_ERROR,
				"ast_read() on chan '%s' called with no recorded file descriptor.\n",
				ast_channel_name(chan));
		}
#endif
	}

	prestate = ast_channel_state(chan);

	if (ast_channel_timingfd(chan) > -1 && ast_channel_fdno(chan) == AST_TIMING_FD) {
		enum ast_timer_event res;

		ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);

		res = ast_timer_get_event(ast_channel_timer(chan));

		switch (res) {
		case AST_TIMING_EVENT_EXPIRED:
			if (ast_timer_ack(ast_channel_timer(chan), 1) < 0) {
				ast_log(LOG_ERROR, "Failed to acknoweldge timer in ast_read\n");
				goto done;
			}

			if (ast_channel_timingfunc(chan)) {
				/* save a copy of func/data before unlocking the channel */
				ast_timing_func_t func = ast_channel_timingfunc(chan);
				void *data = ast_channel_timingdata(chan);
				int got_ref = 0;
				if (data && ast_test_flag(ast_channel_flags(chan), AST_FLAG_TIMINGDATA_IS_AO2_OBJ)) {
					ao2_ref(data, 1);
					got_ref = 1;
				}
				ast_channel_fdno_set(chan, -1);
				ast_channel_unlock(chan);
				func(data);
				if (got_ref) {
					ao2_ref(data, -1);
				}
			} else {
				ast_timer_set_rate(ast_channel_timer(chan), 0);
				ast_channel_fdno_set(chan, -1);
				ast_channel_unlock(chan);
			}

			/* cannot 'goto done' because the channel is already unlocked */
			return &ast_null_frame;

		case AST_TIMING_EVENT_CONTINUOUS:
			if (AST_LIST_EMPTY(ast_channel_readq(chan)) ||
				!AST_LIST_NEXT(AST_LIST_FIRST(ast_channel_readq(chan)), frame_list)) {
				ast_timer_disable_continuous(ast_channel_timer(chan));
			}
			break;
		}

	} else if (ast_channel_fd_isset(chan, AST_GENERATOR_FD) && ast_channel_fdno(chan) == AST_GENERATOR_FD) {
		/* if the AST_GENERATOR_FD is set, call the generator with args
		 * set to -1 so it can do whatever it needs to.
		 */
		void *tmp = ast_channel_generatordata(chan);
		ast_channel_generatordata_set(chan, NULL);     /* reset to let ast_write get through */
		ast_channel_generator(chan)->generate(chan, tmp, -1, -1);
		ast_channel_generatordata_set(chan, tmp);
		f = &ast_null_frame;
		ast_channel_fdno_set(chan, -1);
		goto done;
	} else if (ast_channel_fd_isset(chan, AST_JITTERBUFFER_FD) && ast_channel_fdno(chan) == AST_JITTERBUFFER_FD) {
		ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
	}

	/* Read and ignore anything on the alertpipe, but read only
	   one sizeof(blah) per frame that we send from it */
	if (ast_channel_internal_alert_read(chan) == AST_ALERT_READ_FATAL) {
		f = &ast_null_frame;
		goto done;
	}

	/* Check for pending read queue */
	if (!AST_LIST_EMPTY(ast_channel_readq(chan))) {
		int skip_dtmf = should_skip_dtmf(chan);

		AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), f, frame_list) {
			/* We have to be picky about which frame we pull off of the readq because
			 * there are cases where we want to leave DTMF frames on the queue until
			 * some later time. */

			if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
				continue;
			}

			AST_LIST_REMOVE_CURRENT(frame_list);
			break;
		}
		AST_LIST_TRAVERSE_SAFE_END;

		if (!f) {
			/* There were no acceptable frames on the readq. */
			f = &ast_null_frame;
			ast_channel_alert_write(chan);
		}

		/* Interpret hangup and end-of-Q frames to return NULL */
		/* XXX why not the same for frames from the channel ? */
		if (f->frametype == AST_FRAME_CONTROL) {
			switch (f->subclass.integer) {
			case AST_CONTROL_HANGUP:
				ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
				cause = f->data.uint32;
				/* Fall through */
			case AST_CONTROL_END_OF_Q:
				ast_frfree(f);
				f = NULL;
				break;
			default:
				break;
			}
		} else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
			if (ast_channel_tech(chan) && ast_channel_tech(chan)->read_stream) {
				stream = ast_stream_topology_get_stream(ast_channel_get_stream_topology(chan), f->stream_num);
				default_stream = ast_channel_get_default_stream(chan, ast_format_get_type(f->subclass.format));
			} else {
				/* Since this channel driver does not support multistream determine the default stream this frame
				 * originated from and update the frame to include it.
				 */
				stream = default_stream = ast_channel_get_default_stream(chan, ast_format_get_type(f->subclass.format));
				/* In order to allow media to be passed up the underlying media type has to have a format negotiated on
				 * the channel itself. In cases where this hasn't happened the channel driver is incorrectly passing up
				 * a frame for a format that has not been negotiated. If this occurs just drop the frame as we have no
				 * stream that it came from.
				 */
				if (!stream) {
					ast_frfree(f);
					f = &ast_null_frame;
				} else {
					f->stream_num = ast_stream_get_position(stream);
				}
			}
		}
	} else {
		ast_channel_blocker_set(chan, pthread_self());
		if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION)) {
			if (ast_channel_tech(chan)->exception)
				f = ast_channel_tech(chan)->exception(chan);
			else {
				ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", ast_channel_name(chan));
				f = &ast_null_frame;
			}
			/* Clear the exception flag */
			ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
		} else if (ast_channel_tech(chan) && ast_channel_tech(chan)->read_stream) {
			f = ast_channel_tech(chan)->read_stream(chan);

			/* This channel driver supports multistream so the stream_num on the frame is valid, the only
			 * thing different is that we need to find the default stream so we know whether to invoke the
			 * default stream logic or not (such as transcoding).
			 */
			if (f && (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO)) {
				stream = ast_stream_topology_get_stream(ast_channel_get_stream_topology(chan), f->stream_num);
				default_stream = ast_channel_get_default_stream(chan, ast_format_get_type(f->subclass.format));
			}
		} else if (ast_channel_tech(chan) && ast_channel_tech(chan)->read) {
			f = ast_channel_tech(chan)->read(chan);

			/* Since this channel driver does not support multistream determine the default stream this frame
			 * originated from and update the frame to include it.
			 */
			if (f && (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO)) {
				stream = default_stream = ast_channel_get_default_stream(chan, ast_format_get_type(f->subclass.format));
				if (!stream) {
					ast_frfree(f);
					f = &ast_null_frame;
				} else {
					f->stream_num = ast_stream_get_position(stream);
				}
			}
		}
		else
			ast_log(LOG_WARNING, "No read routine on channel %s\n", ast_channel_name(chan));
	}

	if (stream == default_stream) {
		/* Perform the framehook read event here. After the frame enters the framehook list
		 * there is no telling what will happen, <insert mad scientist laugh here>!!! */
		f = ast_framehook_list_read_event(ast_channel_framehooks(chan), f);
	}

	/*
	 * Reset the recorded file descriptor that triggered this read so that we can
	 * easily detect when ast_read() is called without properly using ast_waitfor().
	 */
	ast_channel_fdno_set(chan, -1);

	if (f) {
		struct ast_frame *readq_tail = AST_LIST_LAST(ast_channel_readq(chan));
		struct ast_control_read_action_payload *read_action_payload;
		struct ast_party_connected_line connected;
		int hooked = 0;

		/* if the channel driver returned more than one frame, stuff the excess
		   into the readq for the next ast_read call
		*/
		if (AST_LIST_NEXT(f, frame_list)) {
			ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
			ast_frfree(AST_LIST_NEXT(f, frame_list));
			AST_LIST_NEXT(f, frame_list) = NULL;
		}

		if (dropnondefault && stream != default_stream) {
			/* If the frame originates from a non-default stream and the caller can not handle other streams
			 * absorb the frame and replace it with a null one instead.
			 */
			ast_frfree(f);
			f = &ast_null_frame;
		}

		switch (f->frametype) {
		case AST_FRAME_CONTROL:
			if (f->subclass.integer == AST_CONTROL_ANSWER) {
				if (prestate == AST_STATE_UP && ast_channel_is_bridged(chan)) {
					ast_debug(1, "Dropping duplicate answer!\n");
					ast_frfree(f);
					f = &ast_null_frame;
				} else {
					/*
					 * Mark when outgoing channel answered so we can know how
					 * long the channel has been up.
					 */
					set_channel_answer_time(chan);

					ast_setstate(chan, AST_STATE_UP);
				}
			} else if (f->subclass.integer == AST_CONTROL_READ_ACTION) {
				read_action_payload = f->data.ptr;
				switch (read_action_payload->action) {
				case AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO:
					ast_party_connected_line_init(&connected);
					ast_party_connected_line_copy(&connected, ast_channel_connected(chan));
					if (ast_connected_line_parse_data(read_action_payload->payload,
						read_action_payload->payload_size, &connected)) {
						ast_party_connected_line_free(&connected);
						break;
					}
					ast_channel_unlock(chan);
					if (ast_channel_connected_line_sub(NULL, chan, &connected, 0) &&
						ast_channel_connected_line_macro(NULL, chan, &connected, 1, 0)) {
						ast_indicate_data(chan, AST_CONTROL_CONNECTED_LINE,
							read_action_payload->payload,
							read_action_payload->payload_size);
					}
					ast_party_connected_line_free(&connected);
					ast_channel_lock(chan);
					break;
				}
				ast_frfree(f);
				f = &ast_null_frame;
			} else if (f->subclass.integer == AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE && dropnondefault) {
				/* The caller of this function is incapable of handling streams so we don't accept the change request
				 * and stick to the streams currently on the channel.
				 */
				ast_channel_stream_topology_changed(chan, ast_channel_get_stream_topology(chan));
				ast_frfree(f);
				f = &ast_null_frame;
			} else if (f->subclass.integer == AST_CONTROL_STREAM_TOPOLOGY_CHANGED && dropnondefault) {
				/* The caller of this function is incapable of handling streams so we absorb the notification that the
				 * stream topology has changed.
				 */
				ast_frfree(f);
				f = &ast_null_frame;
			}
			break;
		case AST_FRAME_DTMF_END:
			send_dtmf_end_event(chan, DTMF_RECEIVED, f->subclass.integer, f->len);
			ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass.integer, ast_channel_name(chan), f->len);
			/* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
			if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF) || ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF)) {
				queue_dtmf_readq(chan, f);
				ast_frfree(f);
				f = &ast_null_frame;
			} else if (!ast_test_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
				if (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
				    ast_tvdiff_ms(ast_tvnow(), *ast_channel_dtmf_tv(chan)) < AST_MIN_DTMF_GAP) {
					/* If it hasn't been long enough, defer this digit */
					queue_dtmf_readq(chan, f);
					ast_frfree(f);
					f = &ast_null_frame;
				} else {
					/* There was no begin, turn this into a begin and send the end later */
					struct timeval tv = ast_tvnow();
					f->frametype = AST_FRAME_DTMF_BEGIN;
					ast_set_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF);
					ast_channel_dtmf_digit_to_emulate_set(chan, f->subclass.integer);
					ast_channel_dtmf_tv_set(chan, &tv);
					if (f->len) {
						if (f->len > option_dtmfminduration)
							ast_channel_emulate_dtmf_duration_set(chan, f->len);
						else
							ast_channel_emulate_dtmf_duration_set(chan, option_dtmfminduration);
					} else
						ast_channel_emulate_dtmf_duration_set(chan, AST_DEFAULT_EMULATE_DTMF_DURATION);
					ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass.integer, ast_channel_emulate_dtmf_duration(chan), ast_channel_name(chan));
				}
				if (ast_channel_audiohooks(chan)) {
					struct ast_frame *old_frame = f;
					/*!
					 * \todo XXX It is possible to write a digit to the audiohook twice
					 * if the digit was originally read while the channel was in autoservice. */
					f = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_READ, f);
					if (old_frame != f)
						ast_frfree(old_frame);
				}
			} else {
				struct timeval now = ast_tvnow();
				if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF)) {
					ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
					ast_clear_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF);
					if (!f->len)
						f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));

					/* detect tones that were received on
					 * the wire with durations shorter than
					 * option_dtmfminduration and set f->len
					 * to the actual duration of the DTMF
					 * frames on the wire.  This will cause
					 * dtmf emulation to be triggered later
					 * on.
					 */
					if (ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan)) < option_dtmfminduration) {
						f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
						ast_log(LOG_DTMF, "DTMF end '%c' detected to have actual duration %ld on the wire, emulation will be triggered on %s\n", f->subclass.integer, f->len, ast_channel_name(chan));
					}
				} else if (!f->len) {
					ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
					f->len = option_dtmfminduration;
				}
				if (f->len < option_dtmfminduration && !ast_test_flag(ast_channel_flags(chan), AST_FLAG_END_DTMF_ONLY)) {
					ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %u, emulating on %s\n", f->subclass.integer, f->len, option_dtmfminduration, ast_channel_name(chan));
					ast_set_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF);
					ast_channel_dtmf_digit_to_emulate_set(chan, f->subclass.integer);
					ast_channel_emulate_dtmf_duration_set(chan, option_dtmfminduration - f->len);
					ast_frfree(f);
					f = &ast_null_frame;
				} else {
					ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
					if (f->len < option_dtmfminduration) {
						f->len = option_dtmfminduration;
					}
					ast_channel_dtmf_tv_set(chan, &now);
				}
				if (ast_channel_audiohooks(chan)) {
					struct ast_frame *old_frame = f;
					f = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_READ, f);
					if (old_frame != f)
						ast_frfree(old_frame);
				}
			}
			break;
		case AST_FRAME_DTMF_BEGIN:
			send_dtmf_begin_event(chan, DTMF_RECEIVED, f->subclass.integer);
			ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass.integer, ast_channel_name(chan));
			if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) ||
			    (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
			      ast_tvdiff_ms(ast_tvnow(), *ast_channel_dtmf_tv(chan)) < AST_MIN_DTMF_GAP) ) {
				ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
				ast_frfree(f);
				f = &ast_null_frame;
			} else {
				struct timeval now = ast_tvnow();
				ast_set_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF);
				ast_channel_dtmf_tv_set(chan, &now);
				ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
			}
			break;
		case AST_FRAME_NULL:
			/* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
			 * is reached , because we want to make sure we pass at least one
			 * voice frame through before starting the next digit, to ensure a gap
			 * between DTMF digits. */
			if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF)) {
				struct timeval now = ast_tvnow();
				if (!ast_channel_emulate_dtmf_duration(chan)) {
					ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF);
					ast_channel_dtmf_digit_to_emulate_set(chan, 0);
				} else if (ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan)) >= ast_channel_emulate_dtmf_duration(chan)) {
					ast_channel_emulate_dtmf_duration_set(chan, 0);
					ast_frfree(f);
					f = ast_channel_dtmff(chan);
					f->frametype = AST_FRAME_DTMF_END;
					f->subclass.integer = ast_channel_dtmf_digit_to_emulate(chan);
					f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
					ast_channel_dtmf_tv_set(chan, &now);
					ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF);
					ast_channel_dtmf_digit_to_emulate_set(chan, 0);
					ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, ast_channel_name(chan));
					if (ast_channel_audiohooks(chan)) {
						struct ast_frame *old_frame = f;
						f = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_READ, f);
						if (old_frame != f) {
							ast_frfree(old_frame);
						}
					}
				}
			}
			break;
		case AST_FRAME_VOICE:
			/* If media was received from a non-default stream don't perform any actions, let it just go through */
			if (stream != default_stream) {
				break;
			}

			/* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
			 * is reached , because we want to make sure we pass at least one
			 * voice frame through before starting the next digit, to ensure a gap
			 * between DTMF digits. */
			if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF) && !ast_channel_emulate_dtmf_duration(chan)) {
				ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF);
				ast_channel_dtmf_digit_to_emulate_set(chan, 0);
			}

			if (dropaudio || ast_test_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF)) {
				if (dropaudio)
					ast_read_generator_actions(chan, f);
				ast_frfree(f);
				f = &ast_null_frame;
			}

			if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF) && !ast_test_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF)) {
				struct timeval now = ast_tvnow();
				if (ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan)) >= ast_channel_emulate_dtmf_duration(chan)) {
					ast_channel_emulate_dtmf_duration_set(chan, 0);
					ast_frfree(f);
					f = ast_channel_dtmff(chan);
					f->frametype = AST_FRAME_DTMF_END;
					f->subclass.integer = ast_channel_dtmf_digit_to_emulate(chan);
					f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
					ast_channel_dtmf_tv_set(chan, &now);
					if (ast_channel_audiohooks(chan)) {
						struct ast_frame *old_frame = f;
						f = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_READ, f);
						if (old_frame != f)
							ast_frfree(old_frame);
					}
					ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, ast_channel_name(chan));
				} else {
					/* Drop voice frames while we're still in the middle of the digit */
					ast_frfree(f);
					f = &ast_null_frame;
				}
				break;
			}
			if (f->frametype != AST_FRAME_VOICE) {
				break;
			}
			if (ast_format_cmp(f->subclass.format, ast_channel_rawreadformat(chan)) != AST_FORMAT_CMP_EQUAL
				&& ast_format_cmp(f->subclass.format, ast_channel_readformat(chan)) != AST_FORMAT_CMP_EQUAL) {
				struct ast_format *core_format;

				/*
				 * Note: This frame may not be one of the current native
				 * formats.  We may have gotten it out of the read queue from
				 * a previous multi-frame translation, from a framehook
				 * injected frame, or the device we're talking to isn't
				 * respecting negotiated formats.  Regardless we will accept
				 * all frames.
				 *
				 * Update the read translation path to handle the new format
				 * that just came in.  If the core wants slinear we need to
				 * setup a new translation path because the core is usually
				 * doing something with the audio itself and may not handle
				 * any other format.  e.g., Softmix bridge, holding bridge
				 * announcer channel, recording, AMD...  Otherwise, we'll
				 * setup to pass the frame as is to the core.  In this case
				 * the core doesn't care.  The channel is likely in
				 * autoservice, safesleep, or the channel is in a bridge.
				 * Let the bridge technology deal with format compatibility
				 * between the channels in the bridge.
				 *
				 * Beware of the transcode_via_slin and genericplc options as
				 * they force any transcoding to go through slin on a bridge.
				 * Unfortunately transcode_via_slin is enabled by default and
				 * genericplc is enabled in the codecs.conf.sample file.
				 *
				 * XXX Only updating translation to slinear frames has some
				 * corner cases if slinear is one of the native formats and
				 * there are different sample rates involved.  We might wind
				 * up with conflicting translation paths between channels
				 * where the read translation path on this channel reduces
				 * the sample rate followed by a write translation path on
				 * the peer channel that increases the sample rate.
				 */
				core_format = ast_channel_readformat(chan);
				if (!ast_format_cache_is_slinear(core_format)) {
					core_format = f->subclass.format;
				}
				if (ast_set_read_format_path(chan, f->subclass.format, core_format)) {
					/* Drop frame.  We couldn't make it compatible with the core. */
					ast_frfree(f);
					f = &ast_null_frame;
					break;
				}
			}
			/*
			 * Send frame to audiohooks if present, if frametype is linear, to preserve
			 * functional compatibility with previous behavior. If not linear, hold off
			 * until transcoding is done where we are more likely to have a linear frame
			 */
			if (ast_channel_audiohooks(chan) && ast_format_cache_is_slinear(f->subclass.format)) {
				/* Place hooked after declaration */
				struct ast_frame *old_frame = f;
				hooked = 1;

				f = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_READ, f);
				if (old_frame != f) {
					ast_frfree(old_frame);
				}
			}

			if (ast_channel_monitor(chan) && ast_channel_monitor(chan)->read_stream) {
				/* XXX what does this do ? */
#ifndef MONITOR_CONSTANT_DELAY
				int jump = ast_channel_outsmpl(chan) - ast_channel_insmpl(chan) - 4 * f->samples;
				if (jump >= 0) {
					jump = calc_monitor_jump((ast_channel_outsmpl(chan) - ast_channel_insmpl(chan)),
						ast_format_get_sample_rate(f->subclass.format),
						ast_format_get_sample_rate(ast_channel_monitor(chan)->read_stream->fmt->format));
					if (ast_seekstream(ast_channel_monitor(chan)->read_stream, jump, SEEK_FORCECUR) == -1) {
						ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
					}
					ast_channel_insmpl_set(chan, ast_channel_insmpl(chan) + (ast_channel_outsmpl(chan) - ast_channel_insmpl(chan)) + f->samples);
				} else {
					ast_channel_insmpl_set(chan, ast_channel_insmpl(chan) + f->samples);
				}
#else
				int jump = calc_monitor_jump((ast_channel_outsmpl(chan) - ast_channel_insmpl(chan)),
					ast_format_get_sample_rate(f->subclass.format),
					ast_format_get_sample_rate(ast_channel_monitor(chan)->read_stream->fmt->format));
				if (jump - MONITOR_DELAY >= 0) {
					if (ast_seekstream(ast_channel_monitor(chan)->read_stream, jump - f->samples, SEEK_FORCECUR) == -1) {
						ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
					}
					ast_channel_insmpl(chan) += ast_channel_outsmpl(chan) - ast_channel_insmpl(chan);
				} else {
					ast_channel_insmpl(chan) += f->samples;
				}
#endif
				if (ast_channel_monitor(chan)->state == AST_MONITOR_RUNNING) {
					if (ast_writestream(ast_channel_monitor(chan)->read_stream, f) < 0)
						ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
				}
			}

			if (ast_channel_readtrans(chan)
				&& ast_format_cmp(f->subclass.format, ast_channel_rawreadformat(chan)) == AST_FORMAT_CMP_EQUAL) {
				f = ast_translate(ast_channel_readtrans(chan), f, 1);
				if (!f) {
					f = &ast_null_frame;
				}
			}

			/* Second chance at hooking a linear frame, also the last chance */
			if (ast_channel_audiohooks(chan) && !hooked) {
				struct ast_frame *old_frame = f;

				f = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_READ, f);
				if (old_frame != f) {
					ast_frfree(old_frame);
				}
			}

			/*
			 * It is possible for the translation process on the channel to have
			 * produced multiple frames from the single input frame we passed it; if
			 * this happens, queue the additional frames *before* the frames we may
			 * have queued earlier. if the readq was empty, put them at the head of
			 * the queue, and if it was not, put them just after the frame that was
			 * at the end of the queue.
			 */
			if (AST_LIST_NEXT(f, frame_list)) {
				struct ast_frame *cur, *multi_frame = AST_LIST_NEXT(f, frame_list);

				/* Mark these frames as being re-queued */
				for (cur = multi_frame; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
					ast_set_flag(cur, AST_FRFLAG_REQUEUED);
				}

				if (!readq_tail) {
					ast_queue_frame_head(chan, multi_frame);
				} else {
					__ast_queue_frame(chan, multi_frame, 0, readq_tail);
				}
				ast_frfree(multi_frame);
				AST_LIST_NEXT(f, frame_list) = NULL;
			}

			/*
			 * Run generator sitting on the line if timing device not available
			 * and synchronous generation of outgoing frames is necessary
			 */
			ast_read_generator_actions(chan, f);
			break;
		case AST_FRAME_RTCP:
			/* Incoming RTCP feedback needs to get to the translator for
			 * outgoing media, which means we treat it as an ast_write */
			if (ast_channel_writetrans(chan)) {
				ast_translate(ast_channel_writetrans(chan), f, 0);
			}
			ast_frfree(f);
			f = &ast_null_frame;
		default:
			/* Just pass it on! */
			break;
		}
	} else {
		/* Make sure we always return NULL in the future */
		if (!ast_channel_softhangup_internal_flag(chan)) {
			ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
		}
		if (cause)
			ast_channel_hangupcause_set(chan, cause);
		if (ast_channel_generator(chan))
			ast_deactivate_generator(chan);
		/* We no longer End the CDR here */
	}

	/* High bit prints debugging */
	if (ast_channel_fin(chan) & DEBUGCHAN_FLAG)
		ast_frame_dump(ast_channel_name(chan), f, "<<");
	ast_channel_fin_set(chan, FRAMECOUNT_INC(ast_channel_fin(chan)));

done:
	if (ast_channel_music_state(chan) && ast_channel_generator(chan) && ast_channel_generator(chan)->digit && f && f->frametype == AST_FRAME_DTMF_END)
		ast_channel_generator(chan)->digit(chan, f->subclass.integer);

	if (ast_channel_audiohooks(chan) && ast_audiohook_write_list_empty(ast_channel_audiohooks(chan))) {
		/* The list gets recreated if audiohooks are added again later */
		ast_audiohook_detach_list(ast_channel_audiohooks(chan));
		ast_channel_audiohooks_set(chan, NULL);
	}
	ast_channel_unlock(chan);
	return f;
}

struct ast_frame *ast_read(struct ast_channel *chan)
{
	return __ast_read(chan, 0, 1);
}

struct ast_frame *ast_read_stream(struct ast_channel *chan)
{
	return __ast_read(chan, 0, 0);
}

struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
{
	return __ast_read(chan, 1, 1);
}

struct ast_frame *ast_read_stream_noaudio(struct ast_channel *chan)
{
	return __ast_read(chan, 1, 0);
}

int ast_indicate(struct ast_channel *chan, int condition)
{
	return ast_indicate_data(chan, condition, NULL, 0);
}

static int attribute_const is_visible_indication(enum ast_control_frame_type condition)
{
	/* Don't include a default case here so that we get compiler warnings
	 * when a new type is added. */

	switch (condition) {
	case AST_CONTROL_PROGRESS:
	case AST_CONTROL_PROCEEDING:
	case AST_CONTROL_VIDUPDATE:
	case AST_CONTROL_SRCUPDATE:
	case AST_CONTROL_SRCCHANGE:
	case AST_CONTROL_RADIO_KEY:
	case AST_CONTROL_RADIO_UNKEY:
	case AST_CONTROL_OPTION:
	case AST_CONTROL_WINK:
	case AST_CONTROL_FLASH:
	case AST_CONTROL_OFFHOOK:
	case AST_CONTROL_TAKEOFFHOOK:
	case AST_CONTROL_ANSWER:
	case AST_CONTROL_HANGUP:
	case AST_CONTROL_CONNECTED_LINE:
	case AST_CONTROL_REDIRECTING:
	case AST_CONTROL_TRANSFER:
	case AST_CONTROL_T38_PARAMETERS:
	case _XXX_AST_CONTROL_T38:
	case AST_CONTROL_CC:
	case AST_CONTROL_READ_ACTION:
	case AST_CONTROL_AOC:
	case AST_CONTROL_END_OF_Q:
	case AST_CONTROL_MCID:
	case AST_CONTROL_UPDATE_RTP_PEER:
	case AST_CONTROL_PVT_CAUSE_CODE:
	case AST_CONTROL_MASQUERADE_NOTIFY:
	case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
	case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
	case AST_CONTROL_STREAM_TOPOLOGY_SOURCE_CHANGED:
	case AST_CONTROL_STREAM_STOP:
	case AST_CONTROL_STREAM_SUSPEND:
	case AST_CONTROL_STREAM_REVERSE:
	case AST_CONTROL_STREAM_FORWARD:
	case AST_CONTROL_STREAM_RESTART:
	case AST_CONTROL_RECORD_CANCEL:
	case AST_CONTROL_RECORD_STOP:
	case AST_CONTROL_RECORD_SUSPEND:
	case AST_CONTROL_RECORD_MUTE:
		break;

	case AST_CONTROL_INCOMPLETE:
	case AST_CONTROL_CONGESTION:
	case AST_CONTROL_BUSY:
	case AST_CONTROL_RINGING:
	case AST_CONTROL_RING:
	case AST_CONTROL_HOLD:
		/* You can hear these */
		return 1;

	case AST_CONTROL_UNHOLD:
		/* This is a special case.  You stop hearing this. */
		break;
	}

	return 0;
}

void ast_channel_hangupcause_hash_set(struct ast_channel *chan, const struct ast_control_pvt_cause_code *cause_code, int datalen)
{
	char causevar[256];

	if (ast_channel_dialed_causes_add(chan, cause_code, datalen)) {
		ast_log(LOG_WARNING, "Unable to store hangup cause for %s on %s\n", cause_code->chan_name, ast_channel_name(chan));
	}

	if (cause_code->emulate_sip_cause) {
		snprintf(causevar, sizeof(causevar), "HASH(SIP_CAUSE,%s)", cause_code->chan_name);
		ast_func_write(chan, causevar, cause_code->code);
	}
}

enum ama_flags ast_channel_string2amaflag(const char *flag)
{
	if (!strcasecmp(flag, "default"))
		return DEFAULT_AMA_FLAGS;
	if (!strcasecmp(flag, "omit"))
		return AST_AMA_OMIT;
	if (!strcasecmp(flag, "billing"))
		return AST_AMA_BILLING;
	if (!strcasecmp(flag, "documentation"))
		return AST_AMA_DOCUMENTATION;
	return AST_AMA_NONE;
}

const char *ast_channel_amaflags2string(enum ama_flags flag)
{
	switch (flag) {
	case AST_AMA_OMIT:
		return "OMIT";
	case AST_AMA_BILLING:
		return "BILLING";
	case AST_AMA_DOCUMENTATION:
		return "DOCUMENTATION";
	default:
		return "Unknown";
	}
}

/*!
 * \internal
 * \brief Preprocess connected line update.
 * \since 12.0.0
 *
 * \param chan channel to change the indication
 * \param data pointer to payload data
 * \param datalen size of payload data
 *
 * \note This function assumes chan is locked.
 *
 * \retval 0 keep going.
 * \retval -1 quit now.
 */
static int indicate_connected_line(struct ast_channel *chan, const void *data, size_t datalen)
{
	struct ast_party_connected_line *chan_connected = ast_channel_connected(chan);
	struct ast_party_connected_line *chan_indicated = ast_channel_connected_indicated(chan);
	struct ast_party_connected_line connected;
	unsigned char current[1024];
	unsigned char proposed[1024];
	int current_size;
	int proposed_size;
	int res;

	ast_party_connected_line_set_init(&connected, chan_connected);
	res = ast_connected_line_parse_data(data, datalen, &connected);
	if (!res) {
		ast_channel_set_connected_line(chan, &connected, NULL);
	}
	ast_party_connected_line_free(&connected);
	if (res) {
		return -1;
	}

	current_size = ast_connected_line_build_data(current, sizeof(current),
		chan_indicated, NULL);
	proposed_size = ast_connected_line_build_data(proposed, sizeof(proposed),
		chan_connected, NULL);
	if (current_size == -1 || proposed_size == -1) {
		return -1;
	}

	if (current_size == proposed_size && !memcmp(current, proposed, current_size)) {
		ast_debug(1, "%s: Dropping redundant connected line update \"%s\" <%s>.\n",
			ast_channel_name(chan),
			S_COR(chan_connected->id.name.valid, chan_connected->id.name.str, ""),
			S_COR(chan_connected->id.number.valid, chan_connected->id.number.str, ""));
		return -1;
	}

	ast_party_connected_line_copy(chan_indicated, chan_connected);
	return 0;
}

/*!
 * \internal
 * \brief Preprocess redirecting update.
 * \since 12.0.0
 *
 * \param chan channel to change the indication
 * \param data pointer to payload data
 * \param datalen size of payload data
 *
 * \note This function assumes chan is locked.
 *
 * \retval 0 keep going.
 * \retval -1 quit now.
 */
static int indicate_redirecting(struct ast_channel *chan, const void *data, size_t datalen)
{
	struct ast_party_redirecting redirecting;
	int res;

	ast_party_redirecting_set_init(&redirecting, ast_channel_redirecting(chan));
	res = ast_redirecting_parse_data(data, datalen, &redirecting);
	if (!res) {
		ast_channel_set_redirecting(chan, &redirecting, NULL);
	}
	ast_party_redirecting_free(&redirecting);
	return res ? -1 : 0;
}

static int indicate_data_internal(struct ast_channel *chan, int _condition, const void *data, size_t datalen)
{
	/* By using an enum, we'll get compiler warnings for values not handled
	 * in switch statements. */
	enum ast_control_frame_type condition = _condition;
	struct ast_tone_zone_sound *ts = NULL;
	const struct ast_control_t38_parameters *t38_parameters;
	int res;

	switch (condition) {
	case AST_CONTROL_CONNECTED_LINE:
		if (indicate_connected_line(chan, data, datalen)) {
			res = 0;
			return res;
		}
		break;
	case AST_CONTROL_REDIRECTING:
		if (indicate_redirecting(chan, data, datalen)) {
			res = 0;
			return res;
		}
		break;
	case AST_CONTROL_HOLD:
	case AST_CONTROL_UNHOLD:
		ast_channel_hold_state_set(chan, _condition);
		break;
	case AST_CONTROL_T38_PARAMETERS:
		t38_parameters = data;
		switch (t38_parameters->request_response) {
		case AST_T38_REQUEST_NEGOTIATE:
		case AST_T38_NEGOTIATED:
			ast_channel_set_is_t38_active_nolock(chan, 1);
			break;
		case AST_T38_REQUEST_TERMINATE:
		case AST_T38_TERMINATED:
		case AST_T38_REFUSED:
			ast_channel_set_is_t38_active_nolock(chan, 0);
			break;
		default:
			break;
		}
		break;
	default:
		break;
	}

	if (is_visible_indication(condition)) {
		/* A new visible indication is requested. */
		ast_channel_visible_indication_set(chan, _condition);
	} else if (condition == AST_CONTROL_UNHOLD || _condition < 0) {
		/* Visible indication is cleared/stopped. */
		ast_channel_visible_indication_set(chan, 0);
	}

	if (ast_channel_tech(chan)->indicate) {
		/* See if the channel driver can handle this condition. */
		res = ast_channel_tech(chan)->indicate(chan, _condition, data, datalen);
	} else {
		res = -1;
	}

	if (!res) {
		/* The channel driver successfully handled this indication */
		res = 0;
		return res;
	}

	/* The channel driver does not support this indication, let's fake
	 * it by doing our own tone generation if applicable. */

	/*!\note If we compare the enumeration type, which does not have any
	 * negative constants, the compiler may optimize this code away.
	 * Therefore, we must perform an integer comparison here. */
	if (_condition < 0) {
		/* Stop any tones that are playing */
		ast_playtones_stop(chan);
		res = 0;
		return res;
	}

	/* Handle conditions that we have tones for. */
	switch (condition) {
	case _XXX_AST_CONTROL_T38:
		/* deprecated T.38 control frame */
		res = -1;
		return res;
	case AST_CONTROL_T38_PARAMETERS:
		/* there is no way to provide 'default' behavior for these
		 * control frames, so we need to return failure, but there
		 * is also no value in the log message below being emitted
		 * since failure to handle these frames is not an 'error'
		 * so just return right now. in addition, we want to return
		 * whatever value the channel driver returned, in case it
		 * has some meaning.*/
		return res;
	case AST_CONTROL_RINGING:
		ts = ast_get_indication_tone(ast_channel_zone(chan), "ring");
		/* It is common practice for channel drivers to return -1 if trying
		 * to indicate ringing on a channel which is up. The idea is to let the
		 * core generate the ringing inband. However, we don't want the
		 * warning message about not being able to handle the specific indication
		 * to print nor do we want ast_indicate_data to return an "error" for this
		 * condition
		 */
		if (ast_channel_state(chan) == AST_STATE_UP) {
			res = 0;
		}
		break;
	case AST_CONTROL_BUSY:
		ts = ast_get_indication_tone(ast_channel_zone(chan), "busy");
		break;
	case AST_CONTROL_INCOMPLETE:
	case AST_CONTROL_CONGESTION:
		ts = ast_get_indication_tone(ast_channel_zone(chan), "congestion");
		break;
	case AST_CONTROL_PVT_CAUSE_CODE:
		ast_channel_hangupcause_hash_set(chan, data, datalen);
		res = 0;
		break;
	case AST_CONTROL_PROGRESS:
	case AST_CONTROL_PROCEEDING:
	case AST_CONTROL_VIDUPDATE:
	case AST_CONTROL_SRCUPDATE:
	case AST_CONTROL_SRCCHANGE:
	case AST_CONTROL_RADIO_KEY:
	case AST_CONTROL_RADIO_UNKEY:
	case AST_CONTROL_OPTION:
	case AST_CONTROL_WINK:
	case AST_CONTROL_FLASH:
	case AST_CONTROL_OFFHOOK:
	case AST_CONTROL_TAKEOFFHOOK:
	case AST_CONTROL_ANSWER:
	case AST_CONTROL_HANGUP:
	case AST_CONTROL_RING:
	case AST_CONTROL_HOLD:
	case AST_CONTROL_UNHOLD:
	case AST_CONTROL_TRANSFER:
	case AST_CONTROL_CONNECTED_LINE:
	case AST_CONTROL_REDIRECTING:
	case AST_CONTROL_CC:
	case AST_CONTROL_READ_ACTION:
	case AST_CONTROL_AOC:
	case AST_CONTROL_END_OF_Q:
	case AST_CONTROL_MCID:
	case AST_CONTROL_MASQUERADE_NOTIFY:
	case AST_CONTROL_UPDATE_RTP_PEER:
	case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
	case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
	case AST_CONTROL_STREAM_TOPOLOGY_SOURCE_CHANGED:
	case AST_CONTROL_STREAM_STOP:
	case AST_CONTROL_STREAM_SUSPEND:
	case AST_CONTROL_STREAM_REVERSE:
	case AST_CONTROL_STREAM_FORWARD:
	case AST_CONTROL_STREAM_RESTART:
	case AST_CONTROL_RECORD_CANCEL:
	case AST_CONTROL_RECORD_STOP:
	case AST_CONTROL_RECORD_SUSPEND:
	case AST_CONTROL_RECORD_MUTE:
		/* Nothing left to do for these. */
		res = 0;
		break;
	}

	if (ts) {
		/* We have a tone to play, yay. */
		ast_debug(1, "Driver for channel '%s' does not support indication %u, emulating it\n", ast_channel_name(chan), condition);
		res = ast_playtones_start(chan, 0, ts->data, 1);
		if (!res) {
			ast_test_suite_event_notify("RINGING_INBAND",
					"Channel: %s\r\n",
					ast_channel_name(chan));
		}
		ts = ast_tone_zone_sound_unref(ts);
	}

	if (res) {
		/* not handled */
		ast_log(LOG_WARNING, "Unable to handle indication %u for '%s'\n", condition, ast_channel_name(chan));
	}

	return res;
}

int ast_indicate_data(struct ast_channel *chan, int _condition, const void *data, size_t datalen)
{
	int res;
	/* this frame is used by framehooks. if it is set, we must free it at the end of this function */
	struct ast_frame *awesome_frame = NULL;

	ast_channel_lock(chan);

	/* Don't bother if the channel is about to go away, anyway. */
	if ((ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)
			|| (ast_check_hangup(chan) && !ast_channel_is_leaving_bridge(chan)))
		&& _condition != AST_CONTROL_MASQUERADE_NOTIFY) {
		res = -1;
		goto indicate_cleanup;
	}

	if (!ast_framehook_list_is_empty(ast_channel_framehooks(chan))) {
		/* Do framehooks now, do it, go, go now */
		struct ast_frame frame = {
			.frametype = AST_FRAME_CONTROL,
			.subclass.integer = _condition,
			.data.ptr = (void *) data, /* this cast from const is only okay because we do the ast_frdup below */
			.datalen = datalen
		};

		/* we have now committed to freeing this frame */
		awesome_frame = ast_frdup(&frame);

		/* who knows what we will get back! the anticipation is killing me. */
		awesome_frame = ast_framehook_list_write_event(ast_channel_framehooks(chan),
			awesome_frame);
		if (!awesome_frame
			|| awesome_frame->frametype != AST_FRAME_CONTROL) {
			res = 0;
			goto indicate_cleanup;
		}

		_condition = awesome_frame->subclass.integer;
		data = awesome_frame->data.ptr;
		datalen = awesome_frame->datalen;
	}

	res = indicate_data_internal(chan, _condition, data, datalen);

indicate_cleanup:
	ast_channel_unlock(chan);
	if (awesome_frame) {
		ast_frfree(awesome_frame);
	}

	return res;
}

int ast_recvchar(struct ast_channel *chan, int timeout)
{
	int c;
	char *buf = ast_recvtext(chan, timeout);
	if (buf == NULL)
		return -1;	/* error or timeout */
	c = *(unsigned char *)buf;
	ast_free(buf);
	return c;
}

char *ast_recvtext(struct ast_channel *chan, int timeout)
{
	int res;
	char *buf = NULL;
	struct timeval start = ast_tvnow();
	int ms;

	while ((ms = ast_remaining_ms(start, timeout))) {
		struct ast_frame *f;

		if (ast_check_hangup(chan)) {
			break;
		}
		res = ast_waitfor(chan, ms);
		if (res <= 0)  {/* timeout or error */
			break;
		}
		f = ast_read(chan);
		if (f == NULL) {
			break; /* no frame */
		}
		if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
			ast_frfree(f);
			break;
		} else if (f->frametype == AST_FRAME_TEXT) {		/* what we want */
			buf = ast_strndup((char *) f->data.ptr, f->datalen);	/* dup and break */
			ast_frfree(f);
			break;
		}
		ast_frfree(f);
	}
	return buf;
}

int ast_sendtext(struct ast_channel *chan, const char *text)
{
	int res = 0;

	ast_channel_lock(chan);
	/* Stop if we're a zombie or need a soft hangup */
	if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
		ast_channel_unlock(chan);
		return -1;
	}

	if (ast_strlen_zero(text)) {
		ast_channel_unlock(chan);
		return 0;
	}

	CHECK_BLOCKING(chan);
	if (ast_channel_tech(chan)->write_text && (ast_format_cap_has_type(ast_channel_nativeformats(chan), AST_MEDIA_TYPE_TEXT))) {
		struct ast_frame f;

		memset(&f, 0, sizeof(f));
		f.frametype = AST_FRAME_TEXT;
		f.src = "DIALPLAN";
		f.mallocd = AST_MALLOCD_DATA;
		f.datalen = strlen(text);
		f.data.ptr = ast_strdup(text);
		f.subclass.format = ast_format_t140;

		if (f.data.ptr) {
			res = ast_channel_tech(chan)->write_text(chan, &f);
			ast_frfree(&f);
		}
	} else if (ast_channel_tech(chan)->send_text) {
		res = ast_channel_tech(chan)->send_text(chan, text);
	}
	ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
	ast_channel_unlock(chan);
	return res;
}

int ast_senddigit_begin(struct ast_channel *chan, char digit)
{
	/* Device does not support DTMF tones, lets fake
	 * it by doing our own generation. */
	static const char * const dtmf_tones[] = {
		"941+1336", /* 0 */
		"697+1209", /* 1 */
		"697+1336", /* 2 */
		"697+1477", /* 3 */
		"770+1209", /* 4 */
		"770+1336", /* 5 */
		"770+1477", /* 6 */
		"852+1209", /* 7 */
		"852+1336", /* 8 */
		"852+1477", /* 9 */
		"697+1633", /* A */
		"770+1633", /* B */
		"852+1633", /* C */
		"941+1633", /* D */
		"941+1209", /* * */
		"941+1477"  /* # */
	};

	if (!ast_channel_tech(chan)->send_digit_begin)
		return 0;

	ast_channel_lock(chan);
	ast_channel_sending_dtmf_digit_set(chan, digit);
	ast_channel_sending_dtmf_tv_set(chan, ast_tvnow());
	ast_channel_unlock(chan);

	if (!ast_channel_tech(chan)->send_digit_begin(chan, digit))
		return 0;

	if (digit >= '0' && digit <='9')
		ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
	else if (digit >= 'A' && digit <= 'D')
		ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
	else if (digit == '*')
		ast_playtones_start(chan, 0, dtmf_tones[14], 0);
	else if (digit == '#')
		ast_playtones_start(chan, 0, dtmf_tones[15], 0);
	else {
		/* not handled */
		ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, ast_channel_name(chan));
	}

	return 0;
}

int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
{
	int res = -1;

	if (ast_channel_tech(chan)->send_digit_end)
		res = ast_channel_tech(chan)->send_digit_end(chan, digit, duration);

	ast_channel_lock(chan);
	if (ast_channel_sending_dtmf_digit(chan) == digit) {
		ast_channel_sending_dtmf_digit_set(chan, 0);
	}
	ast_channel_unlock(chan);

	if (res && ast_channel_generator(chan))
		ast_playtones_stop(chan);

	return 0;
}

int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
{
	if (ast_channel_tech(chan)->send_digit_begin) {
		ast_senddigit_begin(chan, digit);
		ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
	}

	return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
}

int ast_prod(struct ast_channel *chan)
{
	struct ast_frame a = { AST_FRAME_VOICE };
	char nothing[128];

	/* Send an empty audio frame to get things moving */
	if (ast_channel_state(chan) != AST_STATE_UP) {
		ast_debug(1, "Prodding channel '%s'\n", ast_channel_name(chan));
		a.subclass.format = ast_channel_rawwriteformat(chan);
		a.data.ptr = nothing + AST_FRIENDLY_OFFSET;
		a.src = "ast_prod"; /* this better match check in ast_write */
		if (ast_write(chan, &a))
			ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", ast_channel_name(chan));
	}
	return 0;
}

int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
{
	int res;
	if (!ast_channel_tech(chan)->write_video)
		return 0;
	res = ast_write(chan, fr);
	if (!res)
		res = 1;
	return res;
}

struct plc_ds {
	/* A buffer in which to store SLIN PLC
	 * samples generated by the generic PLC
	 * functionality in plc.c
	 */
	int16_t *samples_buf;
	/* The current number of samples in the
	 * samples_buf
	 */
	size_t num_samples;
	plc_state_t plc_state;
};

static void plc_ds_destroy(void *data)
{
	struct plc_ds *plc = data;
	ast_free(plc->samples_buf);
	ast_free(plc);
}

static const struct ast_datastore_info plc_ds_info = {
	.type = "plc",
	.destroy = plc_ds_destroy,
};

static void adjust_frame_for_plc(struct ast_channel *chan, struct ast_frame *frame, struct ast_datastore *datastore)
{
	int num_new_samples = frame->samples;
	struct plc_ds *plc = datastore->data;

	/* As a general note, let me explain the somewhat odd calculations used when taking
	 * the frame offset into account here. According to documentation in frame.h, the frame's
	 * offset field indicates the number of bytes that the audio is offset. The plc->samples_buf
	 * is not an array of bytes, but rather an array of 16-bit integers since it holds SLIN
	 * samples. So I had two choices to make here with the offset.
	 *
	 * 1. Make the offset AST_FRIENDLY_OFFSET bytes. The main downside for this is that
	 *    I can't just add AST_FRIENDLY_OFFSET to the plc->samples_buf and have the pointer
	 *    arithmetic come out right. I would have to do some odd casting or division for this to
	 *    work as I wanted.
	 * 2. Make the offset AST_FRIENDLY_OFFSET * 2 bytes. This allows the pointer arithmetic
	 *    to work out better with the plc->samples_buf. The downside here is that the buffer's
	 *    allocation contains an extra 64 bytes of unused space.
	 *
	 * I decided to go with option 2. This is why in the calloc statement and the statement that
	 * sets the frame's offset, AST_FRIENDLY_OFFSET is multiplied by 2.
	 */

	/* If this audio frame has no samples to fill in, ignore it */
	if (!num_new_samples) {
		return;
	}

	/* First, we need to be sure that our buffer is large enough to accomodate
	 * the samples we need to fill in. This will likely only occur on the first
	 * frame we write.
	 */
	if (plc->num_samples < num_new_samples) {
		ast_free(plc->samples_buf);
		plc->samples_buf = ast_calloc(1, (num_new_samples * sizeof(*plc->samples_buf)) + (AST_FRIENDLY_OFFSET * 2));
		if (!plc->samples_buf) {
			ast_channel_datastore_remove(chan, datastore);
			ast_datastore_free(datastore);
			return;
		}
		plc->num_samples = num_new_samples;
	}

	if (frame->datalen == 0) {
		plc_fillin(&plc->plc_state, plc->samples_buf + AST_FRIENDLY_OFFSET, frame->samples);
		frame->data.ptr = plc->samples_buf + AST_FRIENDLY_OFFSET;
		frame->datalen = num_new_samples * 2;
		frame->offset = AST_FRIENDLY_OFFSET * 2;
	} else {
		plc_rx(&plc->plc_state, frame->data.ptr, frame->samples);
	}
}

static void apply_plc(struct ast_channel *chan, struct ast_frame *frame)
{
	struct ast_datastore *datastore;
	struct plc_ds *plc;

	datastore = ast_channel_datastore_find(chan, &plc_ds_info, NULL);
	if (datastore) {
		plc = datastore->data;
		adjust_frame_for_plc(chan, frame, datastore);
		return;
	}

	datastore = ast_datastore_alloc(&plc_ds_info, NULL);
	if (!datastore) {
		return;
	}
	plc = ast_calloc(1, sizeof(*plc));
	if (!plc) {
		ast_datastore_free(datastore);
		return;
	}
	datastore->data = plc;
	ast_channel_datastore_add(chan, datastore);
	adjust_frame_for_plc(chan, frame, datastore);
}

int ast_write(struct ast_channel *chan, struct ast_frame *fr)
{
	return ast_write_stream(chan, -1, fr);
}

int ast_write_stream(struct ast_channel *chan, int stream_num, struct ast_frame *fr)
{
	struct ast_stream *stream = NULL, *default_stream = NULL;
	int res = -1;
	struct ast_frame *f = NULL;
	int count = 0;
	int hooked = 0;

	/*Deadlock avoidance*/
	while(ast_channel_trylock(chan)) {
		/*cannot goto done since the channel is not locked*/
		if(count++ > 10) {
			ast_debug(1, "Deadlock avoided for write to channel '%s'\n", ast_channel_name(chan));
			return 0;
		}
		usleep(1);
	}

	/* Stop if we're a zombie or need a soft hangup */
	if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
		goto done;
	}

	if (stream_num >= 0) {
		/* If we were told to write to an explicit stream then allow this frame through, no matter
		 * if the type is expected or not (a framehook could change)
		 */
		if (stream_num >= ast_stream_topology_get_count(ast_channel_get_stream_topology(chan))) {
			goto done;
		}
		stream = ast_stream_topology_get_stream(ast_channel_get_stream_topology(chan), stream_num);
		default_stream = ast_channel_get_default_stream(chan, ast_stream_get_type(stream));
	} else if (fr->frametype == AST_FRAME_VOICE || fr->frametype == AST_FRAME_VIDEO || fr->frametype == AST_FRAME_MODEM) {
		/* If we haven't been told of a stream then we need to figure out which once we need */
		enum ast_media_type type = AST_MEDIA_TYPE_UNKNOWN;

		/* Some frame types have a fixed media type */
		if (fr->frametype == AST_FRAME_VOICE || fr->frametype == AST_FRAME_VIDEO) {
			type = ast_format_get_type(fr->subclass.format);
		} else if (fr->frametype == AST_FRAME_MODEM) {
			type = AST_MEDIA_TYPE_IMAGE;
		}

		/* No stream was specified, so use the default one */
		stream = default_stream = ast_channel_get_default_stream(chan, type);
	}

	/* Perform the framehook write event here. After the frame enters the framehook list
	 * there is no telling what will happen, how awesome is that!!! */
	if ((stream == default_stream) && !(fr = ast_framehook_list_write_event(ast_channel_framehooks(chan), fr))) {
		res = 0;
		goto done;
	}

	if (ast_channel_generatordata(chan) && (!fr->src || strcasecmp(fr->src, "ast_prod"))) {
		if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT)) {
				ast_deactivate_generator(chan);
		} else {
			if (fr->frametype == AST_FRAME_DTMF_END) {
				/* There is a generator running while we're in the middle of a digit.
				 * It's probably inband DTMF, so go ahead and pass it so it can
				 * stop the generator */
				ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
				ast_channel_unlock(chan);
				res = ast_senddigit_end(chan, fr->subclass.integer, fr->len);
				ast_channel_lock(chan);
				CHECK_BLOCKING(chan);
			} else if (fr->frametype == AST_FRAME_CONTROL
				&& fr->subclass.integer == AST_CONTROL_UNHOLD) {
				/*
				 * This is a side case where Echo is basically being called
				 * and the person put themselves on hold and took themselves
				 * off hold.
				 */
				indicate_data_internal(chan, fr->subclass.integer, fr->data.ptr,
					fr->datalen);
			}
			res = 0;	/* XXX explain, why 0 ? */
			goto done;
		}
	}
	/* High bit prints debugging */
	if (ast_channel_fout(chan) & DEBUGCHAN_FLAG)
		ast_frame_dump(ast_channel_name(chan), fr, ">>");
	CHECK_BLOCKING(chan);
	switch (fr->frametype) {
	case AST_FRAME_CONTROL:
		indicate_data_internal(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
		res = 0;
		break;
	case AST_FRAME_DTMF_BEGIN:
		if (ast_channel_audiohooks(chan)) {
			struct ast_frame *old_frame = fr;
			fr = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_WRITE, fr);
			if (old_frame != fr)
				f = fr;
		}
		send_dtmf_begin_event(chan, DTMF_SENT, fr->subclass.integer);
		ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
		ast_channel_unlock(chan);
		res = ast_senddigit_begin(chan, fr->subclass.integer);
		ast_channel_lock(chan);
		CHECK_BLOCKING(chan);
		break;
	case AST_FRAME_DTMF_END:
		if (ast_channel_audiohooks(chan)) {
			struct ast_frame *new_frame = fr;

			new_frame = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_WRITE, fr);
			if (new_frame != fr) {
				ast_frfree(new_frame);
			}
		}
		send_dtmf_end_event(chan, DTMF_SENT, fr->subclass.integer, fr->len);
		ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
		ast_channel_unlock(chan);
		res = ast_senddigit_end(chan, fr->subclass.integer, fr->len);
		ast_channel_lock(chan);
		CHECK_BLOCKING(chan);
		break;
	case AST_FRAME_TEXT:
		if (ast_format_cmp(fr->subclass.format, ast_format_t140) == AST_FORMAT_CMP_EQUAL) {
			res = (ast_channel_tech(chan)->write_text == NULL) ? 0 :
				ast_channel_tech(chan)->write_text(chan, fr);
		} else {
			res = (ast_channel_tech(chan)->send_text == NULL) ? 0 :
				ast_channel_tech(chan)->send_text(chan, (char *) fr->data.ptr);
		}
		break;
	case AST_FRAME_HTML:
		res = (ast_channel_tech(chan)->send_html == NULL) ? 0 :
			ast_channel_tech(chan)->send_html(chan, fr->subclass.integer, (char *) fr->data.ptr, fr->datalen);
		break;
	case AST_FRAME_VIDEO:
		/* XXX Handle translation of video codecs one day XXX */
		if (ast_channel_tech(chan)->write_stream) {
			if (stream) {
				res = ast_channel_tech(chan)->write_stream(chan, ast_stream_get_position(stream), fr);
			} else {
				res = 0;
			}
		} else if ((stream == default_stream) && ast_channel_tech(chan)->write_video) {
			res = ast_channel_tech(chan)->write_video(chan, fr);
		} else {
			res = 0;
		}
		break;
	case AST_FRAME_MODEM:
		if (ast_channel_tech(chan)->write_stream) {
			if (stream) {
				res = ast_channel_tech(chan)->write_stream(chan, ast_stream_get_position(stream), fr);
			} else {
				res = 0;
			}
		} else if ((stream == default_stream) && ast_channel_tech(chan)->write) {
			res = ast_channel_tech(chan)->write(chan, fr);
		} else {
			res = 0;
		}
		break;
	case AST_FRAME_VOICE:
		if (ast_opt_generic_plc && ast_format_cmp(fr->subclass.format, ast_format_slin) == AST_FORMAT_CMP_EQUAL) {
			apply_plc(chan, fr);
		}

		f = fr;

		/*
		 * Send frame to audiohooks if present, if frametype is linear (else, later as per
		 * previous behavior)
		 */
		if ((stream == default_stream) && ast_channel_audiohooks(chan)) {
			if (ast_format_cache_is_slinear(fr->subclass.format)) {
				hooked = 1;
				f = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_WRITE, fr);
			}
		}

		/* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
		if ((stream == default_stream) && ast_format_cmp(fr->subclass.format, ast_channel_rawwriteformat(chan)) != AST_FORMAT_CMP_EQUAL) {
			if (ast_format_cmp(ast_channel_writeformat(chan), fr->subclass.format) != AST_FORMAT_CMP_EQUAL) {
				struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);

				/*
				 * We are not setup to write this frame.  Things may have changed
				 * on the peer side of the world and we try to adjust the format to
				 * make it compatible again.  However, bad things can happen if we
				 * cannot setup a new translation path.  Problems range from no
				 * audio, one-way audio, to garbled audio.  The best we can do is
				 * request the call to hangup since we could not make it compatible.
				 *
				 * Being continuously spammed by this message likely indicates a
				 * problem with the peer because it cannot make up its mind about
				 * which format to use.
				 */
				ast_debug(1, "Channel %s changing write format from %s to %s, native formats %s\n",
					ast_channel_name(chan),
					ast_format_get_name(ast_channel_writeformat(chan)),
					ast_format_get_name(fr->subclass.format),
					ast_format_cap_get_names(ast_channel_nativeformats(chan), &codec_buf));
				if (ast_set_write_format(chan, fr->subclass.format)) {
					/* Could not handle the new write format.  Induce a hangup. */
					break;
				}
			}

			if (ast_channel_writetrans(chan)) {
				struct ast_frame *trans_frame = ast_translate(ast_channel_writetrans(chan), f, 0);
                               if (trans_frame != f && f != fr) {
                                       /*
                                        * If translate gives us a new frame and so did the audio
                                        * hook then we need to free the one from the audio hook.
                                        */
                                       ast_frfree(f);
                               }
                               f = trans_frame;
                       }
		}

		if (!f) {
			res = 0;
			break;
		}

		if ((stream == default_stream) && ast_channel_audiohooks(chan) && !hooked) {
			struct ast_frame *prev = NULL, *new_frame, *cur, *dup;
			int freeoldlist = 0;

			if (f != fr) {
				freeoldlist = 1;
			}

			/* Since ast_audiohook_write may return a new frame, and the cur frame is
			 * an item in a list of frames, create a new list adding each cur frame back to it
			 * regardless if the cur frame changes or not. */
			for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
				new_frame = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_WRITE, cur);

				/* if this frame is different than cur, preserve the end of the list,
				 * free the old frames, and set cur to be the new frame */
				if (new_frame != cur) {

					/* doing an ast_frisolate here seems silly, but we are not guaranteed the new_frame
					 * isn't part of local storage, meaning if ast_audiohook_write is called multiple
					 * times it may override the previous frame we got from it unless we dup it */
					if ((dup = ast_frisolate(new_frame))) {
						AST_LIST_NEXT(dup, frame_list) = AST_LIST_NEXT(cur, frame_list);
						if (freeoldlist) {
							AST_LIST_NEXT(cur, frame_list) = NULL;
							ast_frfree(cur);
						}
						if (new_frame != dup) {
							ast_frfree(new_frame);
						}
						cur = dup;
					}
				}

				/* now, regardless if cur is new or not, add it to the new list,
				 * if the new list has not started, cur will become the first item. */
				if (prev) {
					AST_LIST_NEXT(prev, frame_list) = cur;
				} else {
					f = cur; /* set f to be the beginning of our new list */
				}
				prev = cur;
			}
		}

		/* If Monitor is running on this channel, then we have to write frames out there too */
		/* the translator on chan->writetrans may have returned multiple frames
		   from the single frame we passed in; if so, feed each one of them to the
		   monitor */
		if ((stream == default_stream) && ast_channel_monitor(chan) && ast_channel_monitor(chan)->write_stream) {
			struct ast_frame *cur;

			for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
			/* XXX must explain this code */
#ifndef MONITOR_CONSTANT_DELAY
				int jump = ast_channel_insmpl(chan) - ast_channel_outsmpl(chan) - 4 * cur->samples;
				if (jump >= 0) {
					jump = calc_monitor_jump((ast_channel_insmpl(chan) - ast_channel_outsmpl(chan)),
					                         ast_format_get_sample_rate(f->subclass.format),
					                         ast_format_get_sample_rate(ast_channel_monitor(chan)->read_stream->fmt->format));
					if (ast_seekstream(ast_channel_monitor(chan)->write_stream, jump, SEEK_FORCECUR) == -1) {
						ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
					}
					ast_channel_outsmpl_set(chan, ast_channel_outsmpl(chan) + (ast_channel_insmpl(chan) - ast_channel_outsmpl(chan)) + cur->samples);
				} else {
					ast_channel_outsmpl_set(chan, ast_channel_outsmpl(chan) + cur->samples);
				}
#else
				int jump = calc_monitor_jump((ast_channel_insmpl(chan) - ast_channel_outsmpl(chan)),
				                             ast_format_get_sample_rate(f->subclass.format),
				                             ast_format_get_sample_rate(ast_channel_monitor(chan)->read_stream->fmt->format));
				if (jump - MONITOR_DELAY >= 0) {
					if (ast_seekstream(ast_channel_monitor(chan)->write_stream, jump - cur->samples, SEEK_FORCECUR) == -1) {
						ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
					}
					ast_channel_outsmpl_set(chan, ast_channel_outsmpl(chan) + ast_channel_insmpl(chan) - ast_channel_outsmpl(chan));
				} else {
					ast_channel_outsmpl_set(chan, ast_channel_outsmpl(chan) + cur->samples);
				}
#endif
				if (ast_channel_monitor(chan)->state == AST_MONITOR_RUNNING) {
					if (ast_writestream(ast_channel_monitor(chan)->write_stream, cur) < 0)
						ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
				}
			}
		}

		/* the translator on chan->writetrans may have returned multiple frames
		   from the single frame we passed in; if so, feed each one of them to the
		   channel, freeing each one after it has been written */
		if ((f != fr) && AST_LIST_NEXT(f, frame_list)) {
			struct ast_frame *cur, *next = NULL;
			unsigned int skip = 0;

			cur = f;
			while (cur) {
				next = AST_LIST_NEXT(cur, frame_list);
				AST_LIST_NEXT(cur, frame_list) = NULL;
				if (!skip) {
					if ((res = ast_channel_tech(chan)->write(chan, cur)) < 0) {
						ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
						skip = 1;
					} else if (next) {
						/* don't do this for the last frame in the list,
						   as the code outside the loop will do it once
						*/
						ast_channel_fout_set(chan, FRAMECOUNT_INC(ast_channel_fout(chan)));
					}
				}
				ast_frfree(cur);
				cur = next;
			}

			/* reset f so the code below doesn't attempt to free it */
			f = NULL;
		} else {
			if (ast_channel_tech(chan)->write_stream) {
				if (stream) {
					res = ast_channel_tech(chan)->write_stream(chan, ast_stream_get_position(stream), f);
				} else {
					res = 0;
				}
			} else if ((stream == default_stream) && ast_channel_tech(chan)->write) {
				res = ast_channel_tech(chan)->write(chan, f);
			} else {
				res = 0;
			}
		}
		break;
	case AST_FRAME_NULL:
	case AST_FRAME_IAX:
		/* Ignore these */
		res = 0;
		break;
	default:
		/* At this point, fr is the incoming frame and f is NULL.  Channels do
		 * not expect to get NULL as a frame pointer and will segfault.  Hence,
		 * we output the original frame passed in. */
		res = ast_channel_tech(chan)->write(chan, fr);
		break;
	}

	if (f && f != fr)
		ast_frfree(f);
	ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);

	/* Consider a write failure to force a soft hangup */
	if (res < 0) {
		ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
	} else {
		ast_channel_fout_set(chan, FRAMECOUNT_INC(ast_channel_fout(chan)));
	}
done:
	if (ast_channel_audiohooks(chan) && ast_audiohook_write_list_empty(ast_channel_audiohooks(chan))) {
		/* The list gets recreated if audiohooks are added again later */
		ast_audiohook_detach_list(ast_channel_audiohooks(chan));
		ast_channel_audiohooks_set(chan, NULL);
	}
	ast_channel_unlock(chan);
	return res;
}

int ast_set_read_format_path(struct ast_channel *chan, struct ast_format *raw_format, struct ast_format *core_format)
{
	struct ast_trans_pvt *trans_old;
	struct ast_trans_pvt *trans_new;

	if (ast_format_cmp(ast_channel_rawreadformat(chan), raw_format) == AST_FORMAT_CMP_EQUAL
		&& ast_format_cmp(ast_channel_readformat(chan), core_format) == AST_FORMAT_CMP_EQUAL) {
		/* Nothing to setup */
		return 0;
	}

	ast_debug(1, "Channel %s setting read format path: %s -> %s\n",
		ast_channel_name(chan),
		ast_format_get_name(raw_format),
		ast_format_get_name(core_format));

	/* Setup new translation path. */
	if (ast_format_cmp(raw_format, core_format) != AST_FORMAT_CMP_EQUAL) {
		trans_new = ast_translator_build_path(core_format, raw_format);
		if (!trans_new) {
			return -1;
		}
	} else {
		/* No translation needed. */
		trans_new = NULL;
	}
	trans_old = ast_channel_readtrans(chan);
	if (trans_old) {
		ast_translator_free_path(trans_old);
	}
	ast_channel_readtrans_set(chan, trans_new);
	ast_channel_set_rawreadformat(chan, raw_format);
	ast_channel_set_readformat(chan, core_format);
	return 0;
}

int ast_set_write_format_path(struct ast_channel *chan, struct ast_format *core_format, struct ast_format *raw_format)
{
	struct ast_trans_pvt *trans_old;
	struct ast_trans_pvt *trans_new;

	if (ast_format_cmp(ast_channel_rawwriteformat(chan), raw_format) == AST_FORMAT_CMP_EQUAL
		&& ast_format_cmp(ast_channel_writeformat(chan), core_format) == AST_FORMAT_CMP_EQUAL) {
		/* Nothing to setup */
		return 0;
	}

	ast_debug(1, "Channel %s setting write format path: %s -> %s\n",
		ast_channel_name(chan),
		ast_format_get_name(core_format),
		ast_format_get_name(raw_format));

	/* Setup new translation path. */
	if (ast_format_cmp(raw_format, core_format) != AST_FORMAT_CMP_EQUAL) {
		trans_new = ast_translator_build_path(raw_format, core_format);
		if (!trans_new) {
			return -1;
		}
	} else {
		/* No translation needed. */
		trans_new = NULL;
	}
	trans_old = ast_channel_writetrans(chan);
	if (trans_old) {
		ast_translator_free_path(trans_old);
	}
	ast_channel_writetrans_set(chan, trans_new);
	ast_channel_set_rawwriteformat(chan, raw_format);
	ast_channel_set_writeformat(chan, core_format);
	return 0;
}

struct set_format_access {
	const char *direction;
	struct ast_trans_pvt *(*get_trans)(const struct ast_channel *chan);
	void (*set_trans)(struct ast_channel *chan, struct ast_trans_pvt *value);
	struct ast_format *(*get_format)(struct ast_channel *chan);
	void (*set_format)(struct ast_channel *chan, struct ast_format *format);
	struct ast_format *(*get_rawformat)(struct ast_channel *chan);
	void (*set_rawformat)(struct ast_channel *chan, struct ast_format *format);
	int setoption;
};

static const struct set_format_access set_format_access_read = {
	.direction = "read",
	.get_trans = ast_channel_readtrans,
	.set_trans = ast_channel_readtrans_set,
	.get_format = ast_channel_readformat,
	.set_format = ast_channel_set_readformat,
	.get_rawformat = ast_channel_rawreadformat,
	.set_rawformat = ast_channel_set_rawreadformat,
	.setoption = AST_OPTION_FORMAT_READ,
};

static const struct set_format_access set_format_access_write = {
	.direction = "write",
	.get_trans = ast_channel_writetrans,
	.set_trans = ast_channel_writetrans_set,
	.get_format = ast_channel_writeformat,
	.set_format = ast_channel_set_writeformat,
	.get_rawformat = ast_channel_rawwriteformat,
	.set_rawformat = ast_channel_set_rawwriteformat,
	.setoption = AST_OPTION_FORMAT_WRITE,
};

static int set_format(struct ast_channel *chan, struct ast_format_cap *cap_set, const int direction, int interleaved_stereo)
{
	struct ast_trans_pvt *trans_pvt;
	struct ast_format_cap *cap_native;
	const struct set_format_access *access;
	struct ast_format *rawformat;
	struct ast_format *format;
	RAII_VAR(struct ast_format *, best_set_fmt, NULL, ao2_cleanup);
	RAII_VAR(struct ast_format *, best_native_fmt, NULL, ao2_cleanup);
	int res;

	if (!direction) {
		/* reading */
		access = &set_format_access_read;
	} else {
		/* writing */
		access = &set_format_access_write;
	}

	best_set_fmt = ast_format_cap_get_best_by_type(cap_set, AST_MEDIA_TYPE_AUDIO);
	if (!best_set_fmt) {
		/*
		 * Not setting any audio formats?
		 * Assume a call without any sounds (video, text)
		 */
		return 0;
	}

	/* See if the underlying channel driver is capable of performing transcoding for us */
	res = ast_channel_setoption(chan, access->setoption,
		&best_set_fmt, sizeof(best_set_fmt), 0);
	if (!res) {
		ast_debug(1, "Channel driver natively set channel %s to %s format %s\n",
			ast_channel_name(chan), access->direction, ast_format_get_name(best_set_fmt));

		ast_channel_lock(chan);
		cap_native = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
		if (!cap_native
			|| ast_format_cap_append(cap_native, best_set_fmt, 0)) {
			ast_channel_unlock(chan);
			ao2_cleanup(cap_native);
			return -1;
		}
		ast_channel_nativeformats_set(chan, cap_native);
		ao2_cleanup(cap_native);
		access->set_format(chan, best_set_fmt);
		access->set_rawformat(chan, best_set_fmt);

		trans_pvt = access->get_trans(chan);
		if (trans_pvt) {
			ast_translator_free_path(trans_pvt);
			access->set_trans(chan, NULL);
		}
		ast_channel_unlock(chan);

		/* If there is a generator on the channel, it needs to know about this
		 * change if it is the write format. */
		if (direction && ast_channel_generatordata(chan)) {
			generator_write_format_change(chan);
		}

		return 0;
	}

	ast_channel_lock(chan);

	format = access->get_format(chan);
	rawformat = access->get_rawformat(chan);
	ast_assert(format != NULL);
	ast_assert(rawformat != NULL);

	cap_native = ast_channel_nativeformats(chan);
	if (ast_format_cap_empty(cap_native)) {
		ast_channel_unlock(chan);
		ast_log(LOG_ERROR, "Unable to set format because channel %s supports no formats\n",
				ast_channel_name(chan));
		return -1;
	}

	/* Find a translation path from the native format to one of the desired formats */
	if (!direction) {
		/* reading */
		res = ast_translator_best_choice(cap_set, cap_native, &best_set_fmt, &best_native_fmt);
	} else {
		/* writing */
		res = ast_translator_best_choice(cap_native, cap_set, &best_native_fmt, &best_set_fmt);
	}
	if (res < 0) {
		struct ast_str *codec_native = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
		struct ast_str *codec_set = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);

		ast_format_cap_get_names(cap_native, &codec_native);
		ast_channel_unlock(chan);
		ast_format_cap_get_names(cap_set, &codec_set);

		ast_log(LOG_WARNING, "Unable to find a codec translation path: %s -> %s\n",
			ast_str_buffer(direction ? codec_set : codec_native),
			ast_str_buffer(direction ? codec_native : codec_set));
		return -1;
	}

	/* Now we have a good choice for both. */
	trans_pvt = access->get_trans(chan);
	if ((ast_format_cmp(rawformat, best_native_fmt) != AST_FORMAT_CMP_NOT_EQUAL) &&
		(ast_format_cmp(format, best_set_fmt) != AST_FORMAT_CMP_NOT_EQUAL) &&
		((ast_format_cmp(rawformat, format) != AST_FORMAT_CMP_NOT_EQUAL) || access->get_trans(chan))) {
		/* the channel is already in these formats, so nothing to do, unless the interleaved format is not set correctly */
		if (trans_pvt != NULL) {
			if (trans_pvt->interleaved_stereo == interleaved_stereo) {
				ast_channel_unlock(chan);
				return 0;
			}
		}
	}

	/* Free any translation we have right now */
	if (trans_pvt) {
		ast_translator_free_path(trans_pvt);
		access->set_trans(chan, NULL);
	}

	/* Build a translation path from the raw format to the desired format */
	if (ast_format_cmp(best_set_fmt, best_native_fmt) != AST_FORMAT_CMP_NOT_EQUAL) {
		/*
		 * If we were able to swap the native format to the format that
		 * has been requested, then there is no need to try to build
		 * a translation path.
		 */
		res = 0;
	} else {
		if (!direction) {
			/* reading */
			trans_pvt = ast_translator_build_path(best_set_fmt, best_native_fmt);
			trans_pvt->interleaved_stereo = 0;
		} else {
			/* writing */
			trans_pvt = ast_translator_build_path(best_native_fmt, best_set_fmt);
			trans_pvt->interleaved_stereo = interleaved_stereo;
		}
		access->set_trans(chan, trans_pvt);
		res = trans_pvt ? 0 : -1;
	}

	if (!res) {
		access->set_format(chan, best_set_fmt);
		access->set_rawformat(chan, best_native_fmt);

		ast_debug(1, "Channel %s setting %s format path: %s -> %s\n",
			ast_channel_name(chan),
			access->direction,
			ast_format_get_name(direction ? best_set_fmt : best_native_fmt),
			ast_format_get_name(direction ? best_native_fmt : best_set_fmt));
	}

	ast_channel_unlock(chan);

	/* If there is a generator on the channel, it needs to know about this
	 * change if it is the write format. */
	if (direction && ast_channel_generatordata(chan)) {
		generator_write_format_change(chan);
	}

	return res;
}

int ast_set_read_format(struct ast_channel *chan, struct ast_format *format)
{
	struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
	int res;

	ast_assert(format != NULL);

	if (!cap) {
		return -1;
	}
	ast_format_cap_append(cap, format, 0);

	res = set_format(chan, cap, 0, 0);

	ao2_cleanup(cap);
	return res;
}

int ast_set_read_format_from_cap(struct ast_channel *chan, struct ast_format_cap *cap)
{
	return set_format(chan, cap, 0, 0);
}

int ast_set_write_format_interleaved_stereo(struct ast_channel *chan, struct ast_format *format)
{
	struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
	int res;

	ast_assert(format != NULL);

	if (!cap) {
		return -1;
	}
	ast_format_cap_append(cap, format, 0);

	res = set_format(chan, cap, 1, 1);

	ao2_cleanup(cap);
	return res;
}

int ast_set_write_format(struct ast_channel *chan, struct ast_format *format)
{
	struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
	int res;

	ast_assert(format != NULL);

	if (!cap) {
		return -1;
	}
	ast_format_cap_append(cap, format, 0);

	res = set_format(chan, cap, 1, 0);

	ao2_cleanup(cap);
	return res;
}

int ast_set_write_format_from_cap(struct ast_channel *chan, struct ast_format_cap *cap)
{
	return set_format(chan, cap, 1, 0);
}

const char *ast_channel_reason2str(int reason)
{
	switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
	{
	case 0:
		return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
	case AST_CONTROL_HANGUP:
		return "Hangup";
	case AST_CONTROL_RING:
		return "Local Ring";
	case AST_CONTROL_RINGING:
		return "Remote end Ringing";
	case AST_CONTROL_ANSWER:
		return "Remote end has Answered";
	case AST_CONTROL_BUSY:
		return "Remote end is Busy";
	case AST_CONTROL_CONGESTION:
		return "Congestion (circuits busy)";
	default:
		return "Unknown Reason!!";
	}
}

static void handle_cause(int cause, int *outstate)
{
	if (outstate) {
		/* compute error and return */
		if (cause == AST_CAUSE_BUSY)
			*outstate = AST_CONTROL_BUSY;
		else if (cause == AST_CAUSE_CONGESTION)
			*outstate = AST_CONTROL_CONGESTION;
		else
			*outstate = 0;
	}
}

/*!
 * \internal
 * \brief Helper function to inherit info from parent channel.
 *
 * \param new_chan Channel inheriting information.
 * \param parent Channel new_chan inherits information.
 * \param orig Channel being replaced by the call forward channel.
 *
 * \return Nothing
 */
static void call_forward_inherit(struct ast_channel *new_chan, struct ast_channel *parent, struct ast_channel *orig)
{
	if (!ast_test_flag(ast_channel_flags(parent), AST_FLAG_ZOMBIE) && !ast_check_hangup(parent)) {
		struct ast_party_redirecting redirecting;

		/*
		 * The parent is not a ZOMBIE or hungup so update it with the
		 * original channel's redirecting information.
		 */
		ast_party_redirecting_init(&redirecting);
		ast_channel_lock(orig);
		ast_party_redirecting_copy(&redirecting, ast_channel_redirecting(orig));
		ast_channel_unlock(orig);
		if (ast_channel_redirecting_sub(orig, parent, &redirecting, 0) &&
			ast_channel_redirecting_macro(orig, parent, &redirecting, 1, 0)) {
			ast_channel_update_redirecting(parent, &redirecting, NULL);
		}
		ast_party_redirecting_free(&redirecting);
	}

	/* Safely inherit variables and datastores from the parent channel. */
	ast_channel_lock_both(parent, new_chan);
	ast_channel_inherit_variables(parent, new_chan);
	ast_channel_datastore_inherit(parent, new_chan);
	ast_max_forwards_decrement(new_chan);
	ast_channel_unlock(new_chan);
	ast_channel_unlock(parent);
}

struct ast_channel *ast_call_forward(struct ast_channel *caller, struct ast_channel *orig, int *timeout, struct ast_format_cap *cap, struct outgoing_helper *oh, int *outstate)
{
	char tmpchan[256];
	char forwarder[AST_CHANNEL_NAME];
	struct ast_channel *new_chan = NULL;
	char *data, *type;
	int cause = 0;
	int res;

	/* gather data and request the new forward channel */
	ast_copy_string(tmpchan, ast_channel_call_forward(orig), sizeof(tmpchan));
	ast_copy_string(forwarder, ast_channel_name(orig), sizeof(forwarder));
	if ((data = strchr(tmpchan, '/'))) {
		*data++ = '\0';
		type = tmpchan;
	} else {
		const char *forward_context;
		ast_channel_lock(orig);
		forward_context = pbx_builtin_getvar_helper(orig, "FORWARD_CONTEXT");
		snprintf(tmpchan, sizeof(tmpchan), "%s@%s", ast_channel_call_forward(orig), S_OR(forward_context, ast_channel_context(orig)));
		ast_channel_unlock(orig);
		data = tmpchan;
		type = "Local";
	}
	if (!(new_chan = ast_request(type, cap, NULL, orig, data, &cause))) {
		ast_log(LOG_NOTICE, "Unable to create channel for call forward to '%s/%s' (cause = %d)\n", type, data, cause);
		handle_cause(cause, outstate);
		ast_hangup(orig);
		return NULL;
	}

	/* Copy/inherit important information into new channel */
	if (oh) {
		if (oh->vars) {
			ast_channel_lock(new_chan);
			ast_set_variables(new_chan, oh->vars);
			ast_channel_unlock(new_chan);
		}
		if (oh->parent_channel) {
			call_forward_inherit(new_chan, oh->parent_channel, orig);
		}
		if (!ast_strlen_zero(oh->account)) {
			ast_channel_lock(new_chan);
			ast_channel_stage_snapshot(new_chan);
			ast_channel_accountcode_set(new_chan, oh->account);
			ast_channel_peeraccount_set(new_chan, oh->account);
			ast_channel_stage_snapshot_done(new_chan);
			ast_channel_unlock(new_chan);
		}
	} else if (caller) { /* no outgoing helper so use caller if available */
		call_forward_inherit(new_chan, caller, orig);
	}

	ast_channel_lock_both(orig, new_chan);
	ast_channel_set_flag(new_chan, AST_FLAG_ORIGINATED);
	pbx_builtin_setvar_helper(new_chan, "FORWARDERNAME", forwarder);
	ast_party_connected_line_copy(ast_channel_connected(new_chan), ast_channel_connected(orig));
	ast_party_redirecting_copy(ast_channel_redirecting(new_chan), ast_channel_redirecting(orig));
	ast_channel_req_accountcodes(new_chan, orig, AST_CHANNEL_REQUESTOR_REPLACEMENT);
	ast_channel_unlock(new_chan);
	ast_channel_unlock(orig);

	/* call new channel */
	res = ast_call(new_chan, data, 0);
	if (timeout) {
		*timeout = res;
	}
	if (res) {
		ast_log(LOG_NOTICE, "Unable to call forward to channel %s/%s\n", type, (char *)data);
		ast_hangup(orig);
		ast_hangup(new_chan);
		return NULL;
	}
	ast_hangup(orig);

	return new_chan;
}

struct ast_channel *__ast_request_and_dial(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *addr, int timeout, int *outstate, const char *cid_num, const char *cid_name, struct outgoing_helper *oh)
{
	int dummy_outstate;
	int cause = 0;
	struct ast_channel *chan;
	int res = 0;
	int last_subclass = 0;
	struct ast_party_connected_line connected;

	if (outstate)
		*outstate = 0;
	else
		outstate = &dummy_outstate;	/* make outstate always a valid pointer */

	chan = ast_request(type, cap, assignedids, requestor, addr, &cause);
	if (!chan) {
		ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, addr);
		handle_cause(cause, outstate);
		return NULL;
	}

	if (oh) {
		if (oh->vars) {
			ast_channel_lock(chan);
			ast_set_variables(chan, oh->vars);
			ast_channel_unlock(chan);
		}
		if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name)) {
			/*
			 * Use the oh values instead of the function parameters for the
			 * outgoing CallerID.
			 */
			cid_num = oh->cid_num;
			cid_name = oh->cid_name;
		}
		if (oh->parent_channel) {
			/* Safely inherit variables and datastores from the parent channel. */
			ast_channel_lock_both(oh->parent_channel, chan);
			ast_channel_inherit_variables(oh->parent_channel, chan);
			ast_channel_datastore_inherit(oh->parent_channel, chan);
			ast_max_forwards_decrement(chan);
			ast_channel_unlock(oh->parent_channel);
			ast_channel_unlock(chan);
		}
		if (!ast_strlen_zero(oh->account)) {
			ast_channel_lock(chan);
			ast_channel_stage_snapshot(chan);
			ast_channel_accountcode_set(chan, oh->account);
			ast_channel_peeraccount_set(chan, oh->account);
			ast_channel_stage_snapshot_done(chan);
			ast_channel_unlock(chan);
		}
	}

	/*
	 * I seems strange to set the CallerID on an outgoing call leg
	 * to whom we are calling, but this function's callers are doing
	 * various Originate methods.  This call leg goes to the local
	 * user.  Once the local user answers, the dialplan needs to be
	 * able to access the CallerID from the CALLERID function as if
	 * the local user had placed this call.
	 */
	ast_set_callerid(chan, cid_num, cid_name, cid_num);

	ast_set_flag(ast_channel_flags(chan), AST_FLAG_ORIGINATED);
	ast_party_connected_line_set_init(&connected, ast_channel_connected(chan));
	if (cid_num) {
		connected.id.number.valid = 1;
		connected.id.number.str = (char *) cid_num;
		connected.id.number.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
	}
	if (cid_name) {
		connected.id.name.valid = 1;
		connected.id.name.str = (char *) cid_name;
		connected.id.name.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
	}
	ast_channel_set_connected_line(chan, &connected, NULL);
	if (requestor) {
		ast_channel_lock_both(chan, (struct ast_channel *) requestor);
		ast_channel_req_accountcodes(chan, requestor, AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
		ast_channel_unlock(chan);
		ast_channel_unlock((struct ast_channel *) requestor);
	}

	if (ast_call(chan, addr, 0)) {	/* ast_call failed... */
		ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, addr);
	} else {
		struct timeval start = ast_tvnow();
		res = 1;	/* mark success in case chan->_state is already AST_STATE_UP */
		while (timeout && ast_channel_state(chan) != AST_STATE_UP) {
			struct ast_frame *f;
			int ms = ast_remaining_ms(start, timeout);

			res = ast_waitfor(chan, ms);
			if (res == 0) { /* timeout, treat it like ringing */
				*outstate = AST_CONTROL_RINGING;
				break;
			}
			if (res < 0) /* error or done */
				break;
			if (!ast_strlen_zero(ast_channel_call_forward(chan))) {
				if (!(chan = ast_call_forward(NULL, chan, NULL, cap, oh, outstate))) {
					return NULL;
				}
				continue;
			}

			f = ast_read(chan);
			if (!f) {
				*outstate = AST_CONTROL_HANGUP;
				res = 0;
				break;
			}
			if (f->frametype == AST_FRAME_CONTROL) {
				switch (f->subclass.integer) {
				case AST_CONTROL_RINGING:	/* record but keep going */
					*outstate = f->subclass.integer;
					break;

				case AST_CONTROL_BUSY:
					*outstate = f->subclass.integer;
					timeout = 0;
					break;

				case AST_CONTROL_INCOMPLETE:
					*outstate = AST_CONTROL_CONGESTION;
					timeout = 0;
					break;

				case AST_CONTROL_CONGESTION:
					*outstate = f->subclass.integer;
					timeout = 0;
					break;

				case AST_CONTROL_ANSWER:
					*outstate = f->subclass.integer;
					timeout = 0;		/* trick to force exit from the while() */
					break;

				case AST_CONTROL_PVT_CAUSE_CODE:
					ast_channel_hangupcause_hash_set(chan, f->data.ptr, f->datalen);
					break;

				case AST_CONTROL_PROGRESS:
					if (oh && oh->connect_on_early_media) {
						*outstate = f->subclass.integer;
						timeout = 0;		/* trick to force exit from the while() */
						break;
					}
					/* Fallthrough */
				/* Ignore these */
				case AST_CONTROL_PROCEEDING:
				case AST_CONTROL_HOLD:
				case AST_CONTROL_UNHOLD:
				case AST_CONTROL_VIDUPDATE:
				case AST_CONTROL_SRCUPDATE:
				case AST_CONTROL_SRCCHANGE:
				case AST_CONTROL_CONNECTED_LINE:
				case AST_CONTROL_REDIRECTING:
				case AST_CONTROL_CC:
				case -1:			/* Ignore -- just stopping indications */
					break;

				default:
					ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass.integer);
				}
				last_subclass = f->subclass.integer;
			}
			ast_frfree(f);
		}
	}

	/* Final fixups */
	if (oh) {
		if (!ast_strlen_zero(oh->context))
			ast_channel_context_set(chan, oh->context);
		if (!ast_strlen_zero(oh->exten))
			ast_channel_exten_set(chan, oh->exten);
		if (oh->priority)
			ast_channel_priority_set(chan, oh->priority);
	}
	if (ast_channel_state(chan) == AST_STATE_UP)
		*outstate = AST_CONTROL_ANSWER;

	if (res <= 0) {
		ast_channel_lock(chan);
		if (AST_CONTROL_RINGING == last_subclass) {
			ast_channel_hangupcause_set(chan, AST_CAUSE_NO_ANSWER);
		}
		ast_channel_unlock(chan);
		ast_hangup(chan);
		chan = NULL;
	}
	return chan;
}

struct ast_channel *ast_request_and_dial(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *addr, int timeout, int *outstate, const char *cidnum, const char *cidname)
{
	return __ast_request_and_dial(type, cap, assignedids, requestor, addr, timeout, outstate, cidnum, cidname, NULL);
}

static int set_security_requirements(const struct ast_channel *requestor, struct ast_channel *out)
{
	int ops[2][2] = {
		{AST_OPTION_SECURE_SIGNALING, 0},
		{AST_OPTION_SECURE_MEDIA, 0},
	};
	int i;
	struct ast_channel *r = (struct ast_channel *) requestor; /* UGLY */
	struct ast_datastore *ds;

	if (!requestor || !out) {
		return 0;
	}

	ast_channel_lock(r);
	if ((ds = ast_channel_datastore_find(r, &secure_call_info, NULL))) {
		struct ast_secure_call_store *encrypt = ds->data;
		ops[0][1] = encrypt->signaling;
		ops[1][1] = encrypt->media;
	} else {
		ast_channel_unlock(r);
		return 0;
	}
	ast_channel_unlock(r);

	for (i = 0; i < 2; i++) {
		if (ops[i][1]) {
			if (ast_channel_setoption(out, ops[i][0], &ops[i][1], sizeof(ops[i][1]), 0)) {
				/* We require a security feature, but the channel won't provide it */
				return -1;
			}
		} else {
			/* We don't care if we can't clear the option on a channel that doesn't support it */
			ast_channel_setoption(out, ops[i][0], &ops[i][1], sizeof(ops[i][1]), 0);
		}
	}

	return 0;
}

static struct ast_channel *request_channel(const char *type, struct ast_format_cap *request_cap, struct ast_stream_topology *topology,
	const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *addr, int *cause)
{
	struct chanlist *chan;
	struct ast_channel *c = NULL;
	int res;
	int foo;

	if (!cause)
		cause = &foo;
	*cause = AST_CAUSE_NOTDEFINED;

	if (AST_RWLIST_RDLOCK(&backends)) {
		ast_log(LOG_WARNING, "Unable to lock technology backend list\n");
		return NULL;
	}

	AST_RWLIST_TRAVERSE(&backends, chan, list) {
		if (strcasecmp(type, chan->tech->type)) {
			continue;
		}

		break;
	}

	AST_RWLIST_UNLOCK(&backends);

	if (!chan) {
		ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
		*cause = AST_CAUSE_NOSUCHDRIVER;
		return NULL;
	}

	/* Allow either format capabilities or stream topology to be provided and adapt */
	if (chan->tech->requester_with_stream_topology) {
		struct ast_stream_topology *tmp_converted_topology = NULL;

		if (!topology && request_cap) {
			/* Turn the requested capabilities into a stream topology */
			topology = tmp_converted_topology = ast_stream_topology_create_from_format_cap(request_cap);
		}

		c = chan->tech->requester_with_stream_topology(type, topology, assignedids, requestor, addr, cause);

		ast_stream_topology_free(tmp_converted_topology);
	} else if (chan->tech->requester) {
		struct ast_format_cap *tmp_converted_cap = NULL;
		struct ast_format_cap *tmp_cap;
		RAII_VAR(struct ast_format *, tmp_fmt, NULL, ao2_cleanup);
		RAII_VAR(struct ast_format *, best_audio_fmt, NULL, ao2_cleanup);
		struct ast_format_cap *joint_cap;

		if (!request_cap && topology) {
			/* Turn the request stream topology into capabilities */
			request_cap = tmp_converted_cap = ast_format_cap_from_stream_topology(topology);
		}

		/* find the best audio format to use */
		tmp_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
		if (tmp_cap) {
			ast_format_cap_append_from_cap(tmp_cap, request_cap, AST_MEDIA_TYPE_AUDIO);
			/* We have audio - is it possible to connect the various calls to each other?
				(Avoid this check for calls without audio, like text+video calls)
			*/
			res = ast_translator_best_choice(tmp_cap, chan->tech->capabilities, &tmp_fmt, &best_audio_fmt);
			ao2_ref(tmp_cap, -1);
			if (res < 0) {
				struct ast_str *tech_codecs = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
				struct ast_str *request_codecs = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);

				ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %s) to %s\n", type,
					ast_format_cap_get_names(chan->tech->capabilities, &tech_codecs),
					ast_format_cap_get_names(request_cap, &request_codecs));
				*cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
				ao2_cleanup(tmp_converted_cap);
				return NULL;
			}
		}

		/* XXX Only the audio format calculated as being the best for translation
		 * purposes is used for the request. This is because we don't have the ability
		 * to signal to the initiator which one of their codecs that was offered is
		 * the one that was selected, particularly in a chain of Local channels.
		 */
		joint_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
		if (!joint_cap) {
			ao2_cleanup(tmp_converted_cap);
			return NULL;
		}
		ast_format_cap_append_from_cap(joint_cap, request_cap, AST_MEDIA_TYPE_UNKNOWN);
		ast_format_cap_remove_by_type(joint_cap, AST_MEDIA_TYPE_AUDIO);
		ast_format_cap_append(joint_cap, best_audio_fmt, 0);
		ao2_cleanup(tmp_converted_cap);

		c = chan->tech->requester(type, joint_cap, assignedids, requestor, addr, cause);
		ao2_ref(joint_cap, -1);
	}

	if (!c) {
		return NULL;
	}

	if (requestor) {
		ast_callid callid;

		ast_channel_lock_both(c, (struct ast_channel *) requestor);

		/* Set the newly created channel's callid to the same as the requestor. */
		callid = ast_channel_callid(requestor);
		if (callid) {
			ast_channel_callid_set(c, callid);
		}

		ast_channel_unlock(c);
		ast_channel_unlock((struct ast_channel *) requestor);
	}

	if (set_security_requirements(requestor, c)) {
		ast_log(LOG_WARNING, "Setting security requirements failed\n");
		ast_hangup(c);
		*cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
		return NULL;
	}

	/* no need to generate a Newchannel event here; it is done in the channel_alloc call */
	return c;
}

struct ast_channel *ast_request(const char *type, struct ast_format_cap *request_cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *addr, int *cause)
{
	return request_channel(type, request_cap, NULL, assignedids, requestor, addr, cause);
}

struct ast_channel *ast_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 *addr, int *cause)
{
	return request_channel(type, NULL, topology, assignedids, requestor, addr, cause);
}

/*!
 * \internal
 * \brief Setup new channel accountcodes from the requestor channel after ast_request().
 * \since 13.0.0
 *
 * \param chan New channel to get accountcodes setup.
 * \param requestor Requesting channel to get accountcodes from.
 * \param relationship What the new channel was created for.
 * \param precious TRUE if pre-existing accountcodes on chan will not be overwritten.
 *
 * \pre The chan and requestor channels are already locked.
 *
 * \return Nothing
 */
static void channel_req_accountcodes(struct ast_channel *chan, const struct ast_channel *requestor, enum ast_channel_requestor_relationship relationship, int precious)
{
	/*
	 * The primary reason for the existence of this function is
	 * so local channels can propagate accountcodes to the ;2
	 * channel before ast_call().
	 *
	 * The secondary reason is to propagate the CHANNEL(peeraccount)
	 * value set before Dial, FollowMe, and Queue while maintaining
	 * the historic straight across accountcode propagation as a
	 * fallback.
	 */
	switch (relationship) {
	case AST_CHANNEL_REQUESTOR_BRIDGE_PEER:
		/* Crossover the requestor's accountcode and peeraccount */
		if (!precious || ast_strlen_zero(ast_channel_accountcode(chan))) {
			/*
			 * The newly created channel does not have an accountcode
			 * or we don't care.
			 */
			if (!ast_strlen_zero(ast_channel_peeraccount(requestor))) {
				/*
				 * Set it to the requestor's peeraccount.  This allows the
				 * dialplan to indicate the accountcode to use when dialing
				 * by setting CHANNEL(peeraccount).
				 */
				ast_channel_accountcode_set(chan, ast_channel_peeraccount(requestor));
			} else if (!precious
				&& !ast_strlen_zero(ast_channel_accountcode(requestor))) {
				/*
				 * Fallback to the historic propagation and set it to the
				 * requestor's accountcode.
				 */
				ast_channel_accountcode_set(chan, ast_channel_accountcode(requestor));
			}
		}
		if (!ast_strlen_zero(ast_channel_accountcode(requestor))) {
			ast_channel_peeraccount_set(chan, ast_channel_accountcode(requestor));
		}
		break;
	case AST_CHANNEL_REQUESTOR_REPLACEMENT:
		/* Pass the requestor's accountcode and peeraccount straight. */
		if (!precious || ast_strlen_zero(ast_channel_accountcode(chan))) {
			/*
			 * The newly created channel does not have an accountcode
			 * or we don't care.
			 */
			if (!ast_strlen_zero(ast_channel_accountcode(requestor))) {
				ast_channel_accountcode_set(chan, ast_channel_accountcode(requestor));
			}
		}
		if (!ast_strlen_zero(ast_channel_peeraccount(requestor))) {
			ast_channel_peeraccount_set(chan, ast_channel_peeraccount(requestor));
		}
		break;
	}
}

void ast_channel_req_accountcodes(struct ast_channel *chan, const struct ast_channel *requestor, enum ast_channel_requestor_relationship relationship)
{
	channel_req_accountcodes(chan, requestor, relationship, 0);
}

void ast_channel_req_accountcodes_precious(struct ast_channel *chan, const struct ast_channel *requestor, enum ast_channel_requestor_relationship relationship)
{
	channel_req_accountcodes(chan, requestor, relationship, 1);
}

int ast_pre_call(struct ast_channel *chan, const char *sub_args)
{
	int (*pre_call)(struct ast_channel *chan, const char *sub_args);

	ast_channel_lock(chan);
	pre_call = ast_channel_tech(chan)->pre_call;
	if (pre_call) {
		int res;

		res = pre_call(chan, sub_args);
		ast_channel_unlock(chan);
		return res;
	}
	ast_channel_unlock(chan);
	return ast_app_exec_sub(NULL, chan, sub_args, 0);
}

int ast_call(struct ast_channel *chan, const char *addr, int timeout)
{
	/* Place an outgoing call, but don't wait any longer than timeout ms before returning.
	   If the remote end does not answer within the timeout, then do NOT hang up, but
	   return anyway.  */
	int res = -1;
	/* Stop if we're a zombie or need a soft hangup */
	ast_channel_lock(chan);
	if (!ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
		if (ast_channel_tech(chan)->call)
			res = ast_channel_tech(chan)->call(chan, addr, timeout);
		ast_set_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
	}
	ast_channel_unlock(chan);
	return res;
}

/*!
  \brief Transfer a call to dest, if the channel supports transfer

  Called by:
	\arg app_transfer
	\arg the manager interface
*/
int ast_transfer(struct ast_channel *chan, char *dest)
{
	int res = -1;

	/* Stop if we're a zombie or need a soft hangup */
	ast_channel_lock(chan);
	if (!ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
		if (ast_channel_tech(chan)->transfer) {
			res = ast_channel_tech(chan)->transfer(chan, dest);
			if (!res)
				res = 1;
		} else
			res = 0;
	}
	ast_channel_unlock(chan);

	if (res <= 0) {
		return res;
	}

	for (;;) {
		struct ast_frame *fr;

		res = ast_waitfor(chan, -1);

		if (res < 0 || !(fr = ast_read(chan))) {
			res = -1;
			break;
		}

		if (fr->frametype == AST_FRAME_CONTROL && fr->subclass.integer == AST_CONTROL_TRANSFER) {
			enum ast_control_transfer *message = fr->data.ptr;

			if (*message == AST_TRANSFER_SUCCESS) {
				res = 1;
			} else {
				res = -1;
			}

			ast_frfree(fr);
			break;
		}

		ast_frfree(fr);
	}

	return res;
}

int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
{
	return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
}

int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
{
	int pos = 0;	/* index in the buffer where we accumulate digits */
	int to = ftimeout;

	struct ast_silence_generator *silgen = NULL;

	/* Stop if we're a zombie or need a soft hangup */
	if (ast_test_flag(ast_channel_flags(c), AST_FLAG_ZOMBIE) || ast_check_hangup(c))
		return -1;
	if (!len)
		return -1;
	for (;;) {
		int d;
		if (ast_channel_stream(c)) {
			d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
			ast_stopstream(c);
			if (!silgen && ast_opt_transmit_silence)
				silgen = ast_channel_start_silence_generator(c);
			usleep(1000);
			if (!d)
				d = ast_waitfordigit_full(c, to, NULL, audiofd, ctrlfd);
		} else {
			if (!silgen && ast_opt_transmit_silence)
				silgen = ast_channel_start_silence_generator(c);
			d = ast_waitfordigit_full(c, to, NULL, audiofd, ctrlfd);
		}
		if (d < 0) {
			ast_channel_stop_silence_generator(c, silgen);
			return AST_GETDATA_FAILED;
		}
		if (d == 0) {
			s[pos] = '\0';
			ast_channel_stop_silence_generator(c, silgen);
			return AST_GETDATA_TIMEOUT;
		}
		if (d == 1) {
			s[pos] = '\0';
			ast_channel_stop_silence_generator(c, silgen);
			return AST_GETDATA_INTERRUPTED;
		}
		if (strchr(enders, d) && (pos == 0)) {
			s[pos] = '\0';
			ast_channel_stop_silence_generator(c, silgen);
			return AST_GETDATA_EMPTY_END_TERMINATED;
		}
		if (!strchr(enders, d)) {
			s[pos++] = d;
		}
		if (strchr(enders, d) || (pos >= len)) {
			s[pos] = '\0';
			ast_channel_stop_silence_generator(c, silgen);
			return AST_GETDATA_COMPLETE;
		}
		to = timeout;
	}
	/* Never reached */
	return 0;
}

int ast_channel_supports_html(struct ast_channel *chan)
{
	return (ast_channel_tech(chan)->send_html) ? 1 : 0;
}

int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
{
	if (ast_channel_tech(chan)->send_html)
		return ast_channel_tech(chan)->send_html(chan, subclass, data, datalen);
	return -1;
}

int ast_channel_sendurl(struct ast_channel *chan, const char *url)
{
	return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
}

/*! \brief Set up translation from one channel to another */
static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
{
	struct ast_format_cap *src_cap;
	struct ast_format_cap *dst_cap;
	RAII_VAR(struct ast_format *, best_src_fmt, NULL, ao2_cleanup);
	RAII_VAR(struct ast_format *, best_dst_fmt, NULL, ao2_cleanup);
	int no_path;

	/*
	 * We cannot short circuit this code because it is possible to ask
	 * to make compatible two channels that are "compatible" because
	 * they already have translation paths setup but together make for
	 * a sub-optimal path.  e.g., The From channel has g722 -> ulaw
	 * and the To channel has ulaw -> g722.  They are "compatible" but
	 * together the translations are unnecessary and the audio loses
	 * fidelity in the process.
	 */

	ast_channel_lock_both(from, to);

	src_cap = ast_channel_nativeformats(from); /* shallow copy, do not destroy */
	dst_cap = ast_channel_nativeformats(to);   /* shallow copy, do not destroy */

	/* If there's no audio in this call, don't bother with trying to find a translation path */
	if (!ast_format_cap_has_type(src_cap, AST_MEDIA_TYPE_AUDIO)
		|| !ast_format_cap_has_type(dst_cap, AST_MEDIA_TYPE_AUDIO)) {
		ast_channel_unlock(to);
		ast_channel_unlock(from);
		return 0;
	}

	no_path = ast_translator_best_choice(dst_cap, src_cap, &best_dst_fmt, &best_src_fmt);

	ast_channel_unlock(to);
	ast_channel_unlock(from);

	if (no_path) {
		ast_log(LOG_WARNING, "No path to translate from %s to %s\n",
			ast_channel_name(from), ast_channel_name(to));
		return -1;
	}

	/* if the best path is not 'pass through', then
	 * transcoding is needed; if desired, force transcode path
	 * to use SLINEAR between channels, but only if there is
	 * no direct conversion available. If generic PLC is
	 * desired, then transcoding via SLINEAR is a requirement
	 * even if the formats are the same.
	 */
	if (ast_opt_generic_plc_on_equal_codecs
		|| (ast_format_cmp(best_dst_fmt, best_src_fmt) == AST_FORMAT_CMP_NOT_EQUAL
			&& (ast_opt_generic_plc || ast_opt_transcode_via_slin))) {

		int use_slin = (ast_format_cache_is_slinear(best_src_fmt)
			|| ast_format_cache_is_slinear(best_dst_fmt))
			? 1 : ast_opt_generic_plc_on_equal_codecs;

		if (use_slin || ast_translate_path_steps(best_dst_fmt, best_src_fmt) != 1) {
			int best_sample_rate = (ast_format_get_sample_rate(best_src_fmt) > ast_format_get_sample_rate(best_dst_fmt)) ?
				ast_format_get_sample_rate(best_src_fmt) : ast_format_get_sample_rate(best_dst_fmt);

			/* pick the best signed linear format based upon what preserves the sample rate the best. */
			ao2_replace(best_src_fmt, ast_format_cache_get_slin_by_rate(best_sample_rate));
		}
	}

	if (ast_set_read_format(from, best_src_fmt)) {
		ast_log(LOG_WARNING, "Unable to set read format on channel %s to %s\n",
			ast_channel_name(from), ast_format_get_name(best_src_fmt));
		return -1;
	}
	if (ast_set_write_format(to, best_src_fmt)) {
		ast_log(LOG_WARNING, "Unable to set write format on channel %s to %s\n",
			ast_channel_name(to), ast_format_get_name(best_src_fmt));
		return -1;
	}
	return 0;
}

int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
{
	/*
	 * Set up translation from the peer to the chan first in case we
	 * need to hear any in-band tones and the other direction fails.
	 */
	if (ast_channel_make_compatible_helper(peer, chan)) {
		return -1;
	}

	/* Set up translation from the chan to the peer */
	if (ast_channel_make_compatible_helper(chan, peer)) {
		return -1;
	}

	return 0;
}

/*! \brief this function simply changes the name of the channel and issues a manager_event
 *         with out unlinking and linking the channel from the ao2_container.  This should
 *         only be used when the channel has already been unlinked from the ao2_container.
 */
static void __ast_change_name_nolink(struct ast_channel *chan, const char *newname)
{
	/*** DOCUMENTATION
		<managerEventInstance>
			<synopsis>Raised when the name of a channel is changed.</synopsis>
		</managerEventInstance>
	***/
	ast_manager_event(chan, EVENT_FLAG_CALL, "Rename",
		"Channel: %s\r\n"
		"Newname: %s\r\n"
		"Uniqueid: %s\r\n",
		ast_channel_name(chan), newname, ast_channel_uniqueid(chan));
	ast_channel_name_set(chan, newname);
}

void ast_change_name(struct ast_channel *chan, const char *newname)
{
	/* We must re-link, as the hash value will change here. */
	ao2_lock(channels);
	ast_channel_lock(chan);
	ao2_unlink(channels, chan);
	__ast_change_name_nolink(chan, newname);
	ao2_link(channels, chan);
	ast_channel_unlock(chan);
	ao2_unlock(channels);
}

void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
{
	struct ast_var_t *current;
	struct ast_var_t *newvar;
	const char *varname;
	int vartype;

	AST_LIST_TRAVERSE(ast_channel_varshead((struct ast_channel *) parent), current, entries) {
		varname = ast_var_full_name(current);
		if (!varname) {
			continue;
		}

		vartype = 0;
		if (varname[0] == '_') {
			vartype = 1;
			if (varname[1] == '_') {
				vartype = 2;
			}
		}

		switch (vartype) {
		case 1:
			newvar = ast_var_assign(&varname[1], ast_var_value(current));
			break;
		case 2:
			newvar = ast_var_assign(varname, ast_var_value(current));
			break;
		default:
			continue;
		}
		if (newvar) {
			ast_debug(1, "Inheriting variable %s from %s to %s.\n",
				ast_var_full_name(newvar), ast_channel_name(parent),
				ast_channel_name(child));
			AST_LIST_INSERT_TAIL(ast_channel_varshead(child), newvar, entries);
			ast_channel_publish_varset(child, ast_var_full_name(newvar),
				ast_var_value(newvar));
		}
	}
}

/*!
  \brief Clone channel variables from 'clone' channel into 'original' channel

  All variables except those related to app_groupcount are cloned.
  Variables are actually _removed_ from 'clone' channel, presumably
  because it will subsequently be destroyed.

  \note Assumes locks will be in place on both channels when called.
*/
static void clone_variables(struct ast_channel *original, struct ast_channel *clonechan)
{
	struct ast_var_t *current, *newvar;
	/* Append variables from clone channel into original channel */
	/* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
	AST_LIST_APPEND_LIST(ast_channel_varshead(original), ast_channel_varshead(clonechan), entries);

	/* then, dup the varshead list into the clone */

	AST_LIST_TRAVERSE(ast_channel_varshead(original), current, entries) {
		newvar = ast_var_assign(current->name, current->value);
		if (newvar)
			AST_LIST_INSERT_TAIL(ast_channel_varshead(clonechan), newvar, entries);
	}
}


void ast_channel_name_to_dial_string(char *channel_name)
{
	char *dash;

	/* Truncate after the dash */
	dash = strrchr(channel_name, '-');
	if (dash) {
		*dash = '\0';
	}
}

/*!
 * \brief Masquerade a channel
 *
 * \note Assumes _NO_ channels and _NO_ channel pvt's are locked.  If a channel is locked while calling
 *       this function, it invalidates our channel container locking order.  All channels
 *       must be unlocked before it is permissible to lock the channels' ao2 container.
 */
static void channel_do_masquerade(struct ast_channel *original, struct ast_channel *clonechan)
{
	int x;
	int origstate;
	unsigned int orig_disablestatecache;
	unsigned int clone_disablestatecache;
	int generator_fd;
	int visible_indication;
	int clone_hold_state;
	int moh_is_playing;
	struct ast_frame *current;
	const struct ast_channel_tech *t;
	void *t_pvt;
	union {
		struct ast_hangup_handler_list handlers;
		struct ast_party_dialed dialed;
		struct ast_party_caller caller;
		struct ast_party_connected_line connected;
		struct ast_party_redirecting redirecting;
	} exchange;
	struct ast_channel *bridged;
	struct ast_format *rformat;
	struct ast_format *wformat;
	struct ast_format *tmp_format;
	struct ast_format_cap *tmp_cap;
	char tmp_name[AST_CHANNEL_NAME];
	char clone_sending_dtmf_digit;
	struct timeval clone_sending_dtmf_tv;

	/* XXX This operation is a bit odd.  We're essentially putting the guts of
	 * the clone channel into the original channel.  Start by killing off the
	 * original channel's backend.  While the features are nice, which is the
	 * reason we're keeping it, it's still awesomely weird. XXX */

	/* Indicate to each channel that a masquerade is about to begin. */
	x = 1;
	ast_indicate_data(original, AST_CONTROL_MASQUERADE_NOTIFY, &x, sizeof(x));
	ast_indicate_data(clonechan, AST_CONTROL_MASQUERADE_NOTIFY, &x, sizeof(x));

	/*
	 * The container lock is necessary for proper locking order
	 * because the channels must be unlinked to change their
	 * names.
	 *
	 * The original and clonechan locks must be held while the
	 * channel contents are shuffled around for the masquerade.
	 *
	 * The masq and masqr pointers need to be left alone until the masquerade
	 * has restabilized the channels to hold off ast_hangup() and until
	 * AST_FLAG_ZOMBIE can be set on the clonechan.
	 */
	ao2_lock(channels);

	/* Bump the refs to ensure that they won't dissapear on us. */
	ast_channel_ref(original);
	ast_channel_ref(clonechan);

	/* unlink from channels container as name (which is the hash value) will change */
	ao2_unlink(channels, original);
	ao2_unlink(channels, clonechan);

	moh_is_playing = ast_test_flag(ast_channel_flags(original), AST_FLAG_MOH);
	if (moh_is_playing) {
		/* Stop MOH on the old original channel. */
		ast_moh_stop(original);
	}

	/*
	 * Stop any visible indication on the original channel so we can
	 * transfer it to the clonechan taking the original's place.
	 */
	ast_channel_lock(original);
	visible_indication = ast_channel_visible_indication(original);
	ast_channel_unlock(original);
	ast_indicate(original, -1);

	/* Start the masquerade channel contents rearangement. */
	ast_channel_lock_both(original, clonechan);

	ast_debug(1, "Actually Masquerading %s(%u) into the structure of %s(%u)\n",
		ast_channel_name(clonechan), ast_channel_state(clonechan),
		ast_channel_name(original), ast_channel_state(original));

	/*
	 * Remember the original read/write formats.  We turn off any
	 * translation on either one
	 */
	rformat = ao2_bump(ast_channel_readformat(original));
	wformat = ao2_bump(ast_channel_writeformat(original));
	free_translation(clonechan);
	free_translation(original);

	clone_hold_state = ast_channel_hold_state(clonechan);

	/* Save the current DTMF digit being sent if any. */
	clone_sending_dtmf_digit = ast_channel_sending_dtmf_digit(clonechan);
	clone_sending_dtmf_tv = ast_channel_sending_dtmf_tv(clonechan);

	/* Swap uniqueid's of the channels. This needs to happen before channel renames,
	 * so rename events get the proper id's.
	 */
	ast_channel_internal_swap_uniqueid_and_linkedid(clonechan, original);

	/* Make sure the Stasis topic on the channel is updated appropriately */
	ast_channel_internal_swap_topics(clonechan, original);

	/* Swap channel names. This uses ast_channel_name_set directly, so we
	 * don't get any spurious rename events.
	 */
	ast_copy_string(tmp_name, ast_channel_name(clonechan), sizeof(tmp_name));
	ast_channel_name_set(clonechan, ast_channel_name(original));
	ast_channel_name_set(original, tmp_name);

	/* Swap the technologies */
	t = ast_channel_tech(original);
	ast_channel_tech_set(original, ast_channel_tech(clonechan));
	ast_channel_tech_set(clonechan, t);

	t_pvt = ast_channel_tech_pvt(original);
	ast_channel_tech_pvt_set(original, ast_channel_tech_pvt(clonechan));
	ast_channel_tech_pvt_set(clonechan, t_pvt);

	/* Swap the alertpipes */
	ast_channel_internal_alertpipe_swap(original, clonechan);

	/*
	 * Swap the readq's.  The end result should be this:
	 *
	 *  1) All frames should be on the new (original) channel.
	 *  2) Any frames that were already on the new channel before this
	 *     masquerade need to be at the end of the readq, after all of the
	 *     frames on the old (clone) channel.
	 *  3) The alertpipe needs to get poked for every frame that was already
	 *     on the new channel, since we are now using the alert pipe from the
	 *     old (clone) channel.
	 */
	{
		AST_LIST_HEAD_NOLOCK(, ast_frame) tmp_readq;

		AST_LIST_HEAD_INIT_NOLOCK(&tmp_readq);
		AST_LIST_APPEND_LIST(&tmp_readq, ast_channel_readq(original), frame_list);
		AST_LIST_APPEND_LIST(ast_channel_readq(original), ast_channel_readq(clonechan), frame_list);

		while ((current = AST_LIST_REMOVE_HEAD(&tmp_readq, frame_list))) {
			AST_LIST_INSERT_TAIL(ast_channel_readq(original), current, frame_list);
			if (ast_channel_alert_write(original)) {
				ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
			}
		}
	}

	/* Swap the raw formats */
	tmp_format = ao2_bump(ast_channel_rawreadformat(original));
	ast_channel_set_rawreadformat(original, ast_channel_rawreadformat(clonechan));
	ast_channel_set_rawreadformat(clonechan, tmp_format);
	ao2_cleanup(tmp_format);

	tmp_format = ao2_bump(ast_channel_rawwriteformat(original));
	ast_channel_set_rawwriteformat(original, ast_channel_rawwriteformat(clonechan));
	ast_channel_set_rawwriteformat(clonechan, tmp_format);
	ao2_cleanup(tmp_format);

	ast_channel_softhangup_internal_flag_set(clonechan, AST_SOFTHANGUP_DEV);

	/* And of course, so does our current state.  Note we need not
	   call ast_setstate since the event manager doesn't really consider
	   these separate.  We do this early so that the clone has the proper
	   state of the original channel. */
	origstate = ast_channel_state(original);
	ast_channel_state_set(original, ast_channel_state(clonechan));
	ast_channel_state_set(clonechan, origstate);

	/* And the swap the cachable state too. Otherwise we'd start caching
	 * Local channels and ignoring real ones. */
	orig_disablestatecache = ast_test_flag(ast_channel_flags(original), AST_FLAG_DISABLE_DEVSTATE_CACHE);
	clone_disablestatecache = ast_test_flag(ast_channel_flags(clonechan), AST_FLAG_DISABLE_DEVSTATE_CACHE);
	if (orig_disablestatecache != clone_disablestatecache) {
		if (orig_disablestatecache) {
			ast_clear_flag(ast_channel_flags(original), AST_FLAG_DISABLE_DEVSTATE_CACHE);
			ast_set_flag(ast_channel_flags(clonechan), AST_FLAG_DISABLE_DEVSTATE_CACHE);
		} else {
			ast_set_flag(ast_channel_flags(original), AST_FLAG_DISABLE_DEVSTATE_CACHE);
			ast_clear_flag(ast_channel_flags(clonechan), AST_FLAG_DISABLE_DEVSTATE_CACHE);
		}
	}

	/* Update the type. */
	t_pvt = ast_channel_monitor(original);
	ast_channel_monitor_set(original, ast_channel_monitor(clonechan));
	ast_channel_monitor_set(clonechan, t_pvt);

	/* Keep the same language.  */
	ast_channel_language_set(original, ast_channel_language(clonechan));

	/* Keep the same parkinglot. */
	ast_channel_parkinglot_set(original, ast_channel_parkinglot(clonechan));

	/* Clear all existing file descriptors but retain the generator */
	generator_fd = ast_channel_fd(original, AST_GENERATOR_FD);
	ast_channel_internal_fd_clear_all(original);
	ast_channel_set_fd(original, AST_GENERATOR_FD, generator_fd);

	/* Copy all file descriptors present on clonechan to original, skipping generator */
	for (x = 0; x < ast_channel_fd_count(clonechan); x++) {
		if (x != AST_GENERATOR_FD)
			ast_channel_set_fd(original, x, ast_channel_fd(clonechan, x));
	}

	ast_app_group_update(clonechan, original);

	/* Swap hangup handlers. */
	exchange.handlers = *ast_channel_hangup_handlers(original);
	*ast_channel_hangup_handlers(original) = *ast_channel_hangup_handlers(clonechan);
	*ast_channel_hangup_handlers(clonechan) = exchange.handlers;

	/* Call fixup handlers for the clone chan */
	if (AST_LIST_FIRST(ast_channel_datastores(clonechan))) {
		struct ast_datastore *ds;
		/* We use a safe traversal here because some fixup routines actually
		 * remove the datastore from the list and free them.
		 */
		AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_datastores(clonechan), ds, entry) {
			if (ds->info->chan_fixup) {
				ds->info->chan_fixup(ds->data, clonechan, original);
			}
		}
		AST_LIST_TRAVERSE_SAFE_END;
	}

	/* Call breakdown handlers for the original chan */
	if (AST_LIST_FIRST(ast_channel_datastores(original))) {
		struct ast_datastore *ds;
		/* We use a safe traversal here because some breakdown routines may
		 * remove the datastore from the list and free them.
		 */
		AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_datastores(original), ds, entry) {
			if (ds->info->chan_breakdown) {
				ds->info->chan_breakdown(ds->data, clonechan, original);
			}
		}
		AST_LIST_TRAVERSE_SAFE_END;
	}

	/* Move data stores over */
	if (AST_LIST_FIRST(ast_channel_datastores(clonechan))) {
		AST_LIST_APPEND_LIST(ast_channel_datastores(original), ast_channel_datastores(clonechan), entry);
	}

	/* Move framehooks over */
	ast_framehook_list_fixup(clonechan, original);

	/* Move audiohooks over */
	ast_audiohook_move_all(clonechan, original);

	ast_autochan_new_channel(clonechan, original);

	clone_variables(original, clonechan);
	/* Presense of ADSI capable CPE follows clone */
	ast_channel_adsicpe_set(original, ast_channel_adsicpe(clonechan));
	/* Bridge remains the same */
	/* CDR fields remain the same */
	/* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
	/* Application and data remain the same */
	/* Clone exception  becomes real one, as with fdno */
	ast_set_flag(ast_channel_flags(original), ast_test_flag(ast_channel_flags(clonechan), AST_FLAG_EXCEPTION | AST_FLAG_OUTGOING));
	ast_channel_fdno_set(original, ast_channel_fdno(clonechan));
	/* Schedule context remains the same */
	/* Stream stuff stays the same */
	/* Keep the original state.  The fixup code will need to work with it most likely */

	/*
	 * Just swap the whole structures, nevermind the allocations,
	 * they'll work themselves out.
	 */
	exchange.dialed = *ast_channel_dialed(original);
	ast_channel_dialed_set(original, ast_channel_dialed(clonechan));
	ast_channel_dialed_set(clonechan, &exchange.dialed);

	/* Reset any earlier private caller id representations */
	ast_party_id_reset(&ast_channel_caller(original)->priv);
	ast_party_id_reset(&ast_channel_caller(clonechan)->priv);

	exchange.caller = *ast_channel_caller(original);
	ast_channel_caller_set(original, ast_channel_caller(clonechan));
	ast_channel_caller_set(clonechan, &exchange.caller);

	/* Reset any earlier private connected id representations */
	ast_party_id_reset(&ast_channel_connected(original)->priv);
	ast_party_id_reset(&ast_channel_connected(clonechan)->priv);

	exchange.connected = *ast_channel_connected(original);
	ast_channel_connected_set(original, ast_channel_connected(clonechan));
	ast_channel_connected_set(clonechan, &exchange.connected);

	/* Reset any earlier private redirecting orig, from or to representations */
	ast_party_id_reset(&ast_channel_redirecting(original)->priv_orig);
	ast_party_id_reset(&ast_channel_redirecting(clonechan)->priv_orig);
	ast_party_id_reset(&ast_channel_redirecting(original)->priv_from);
	ast_party_id_reset(&ast_channel_redirecting(clonechan)->priv_from);
	ast_party_id_reset(&ast_channel_redirecting(original)->priv_to);
	ast_party_id_reset(&ast_channel_redirecting(clonechan)->priv_to);

	exchange.redirecting = *ast_channel_redirecting(original);
	ast_channel_redirecting_set(original, ast_channel_redirecting(clonechan));
	ast_channel_redirecting_set(clonechan, &exchange.redirecting);

	ast_channel_publish_snapshot(original);

	/* Restore original timing file descriptor */
	ast_channel_set_fd(original, AST_TIMING_FD, ast_channel_timingfd(original));

	/* Our native formats are different now */
	tmp_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
	if (tmp_cap) {
		ast_format_cap_append_from_cap(tmp_cap, ast_channel_nativeformats(clonechan), AST_MEDIA_TYPE_UNKNOWN);
		ast_channel_nativeformats_set(original, tmp_cap);
		ao2_ref(tmp_cap, -1);
	}

	/* Context, extension, priority, app data, jump table,  remain the same */
	/* pvt switches.  pbx stays the same, as does next */

	/* Set the write format */
	ast_set_write_format(original, wformat);

	/* Set the read format */
	ast_set_read_format(original, rformat);

	/* Copy the music class */
	ast_channel_musicclass_set(original, ast_channel_musicclass(clonechan));

	/* copy over accuntcode and set peeraccount across the bridge */
	ast_channel_accountcode_set(original, S_OR(ast_channel_accountcode(clonechan), ""));

	ast_debug(1, "Putting channel %s in %s/%s formats\n", ast_channel_name(original),
		ast_format_get_name(wformat), ast_format_get_name(rformat));

	/* Fixup the original clonechan's physical side */
	if (ast_channel_tech(original)->fixup && ast_channel_tech(original)->fixup(clonechan, original)) {
		ast_log(LOG_WARNING, "Channel type '%s' could not fixup channel %s, strange things may happen. (clonechan)\n",
			ast_channel_tech(original)->type, ast_channel_name(original));
	}

	/* Fixup the original original's physical side */
	if (ast_channel_tech(clonechan)->fixup && ast_channel_tech(clonechan)->fixup(original, clonechan)) {
		ast_log(LOG_WARNING, "Channel type '%s' could not fixup channel %s, strange things may happen. (original)\n",
			ast_channel_tech(clonechan)->type, ast_channel_name(clonechan));
	}

	ast_channel_internal_swap_stream_topology(original, clonechan);

	/*
	 * Now, at this point, the "clone" channel is totally F'd up.
	 * We mark it as a zombie so nothing tries to touch it.
	 *
	 * This must be done before we unlock clonechan to prevent
	 * setting up another masquerade on the clonechan.
	 */
	ast_set_flag(ast_channel_flags(clonechan), AST_FLAG_ZOMBIE);
	ast_queue_frame(clonechan, &ast_null_frame);

	ast_channel_unlock(original);
	ast_channel_unlock(clonechan);

	/*
	 * Indicate to each channel that a masquerade is complete.
	 *
	 * We can still do this to clonechan even though it is a
	 * zombie because ast_indicate_data() will explicitly pass
	 * this control and ast_hangup() is held off until the
	 * ast_channel_masq() and ast_channel_masqr() pointers are
	 * cleared.
	 */
	x = 0;
	ast_indicate_data(original, AST_CONTROL_MASQUERADE_NOTIFY, &x, sizeof(x));
	ast_indicate_data(clonechan, AST_CONTROL_MASQUERADE_NOTIFY, &x, sizeof(x));

	ast_bridge_notify_masquerade(original);

	if (clone_hold_state == AST_CONTROL_HOLD) {
		ast_debug(1, "Channel %s simulating UNHOLD for masquerade.\n",
			ast_channel_name(original));
		ast_indicate(original, AST_CONTROL_UNHOLD);
	}
	if (clone_sending_dtmf_digit) {
		/*
		 * The clonechan was sending a DTMF digit that was not completed
		 * before the masquerade.
		 */
		ast_channel_end_dtmf(original, clone_sending_dtmf_digit, clone_sending_dtmf_tv,
			"masquerade");
	}

	/*
	 * If an indication is currently playing, maintain it on the
	 * channel that is taking the place of original.
	 *
	 * This is needed because the masquerade is swapping out the
	 * internals of the channel, and the new channel private data
	 * needs to be made aware of the current visible indication
	 * (RINGING, CONGESTION, etc.)
	 */
	if (visible_indication) {
		if (visible_indication == AST_CONTROL_HOLD) {
			const char *latest_musicclass;
			int len;

			ast_channel_lock(original);
			latest_musicclass = ast_strdupa(ast_channel_latest_musicclass(original));
			ast_channel_unlock(original);
			if (ast_strlen_zero(latest_musicclass)) {
				latest_musicclass = NULL;
				len = 0;
			} else {
				len = strlen(latest_musicclass) + 1;
			}
			ast_indicate_data(original, visible_indication, latest_musicclass, len);
		} else {
			ast_indicate(original, visible_indication);
		}
	}

	/*
	 * If MOH was playing on the original channel then it needs to be
	 * maintained on the channel that is replacing it.
	 */
	if (moh_is_playing) {
		/* Start MOH on the new original channel. */
		ast_moh_start(original, NULL, NULL);
	}

	ast_channel_lock(original);

	/* Signal any blocker */
	if (ast_test_flag(ast_channel_flags(original), AST_FLAG_BLOCKING)) {
		pthread_kill(ast_channel_blocker(original), SIGURG);
	}

	ast_debug(1, "Done Masquerading %s (%u)\n", ast_channel_name(original), ast_channel_state(original));
	ast_channel_unlock(original);

	if ((bridged = ast_channel_bridge_peer(original))) {
		ast_indicate(bridged, AST_CONTROL_SRCCHANGE);
		ast_channel_unref(bridged);
	}
	ast_indicate(original, AST_CONTROL_SRCCHANGE);

	/* Now that the operation is complete, we can clear the masq
	 * and masqr fields of both channels.
	 */
	ast_channel_lock_both(original, clonechan);
	ast_channel_masq_set(original, NULL);
	ast_channel_masqr_set(clonechan, NULL);
	ast_channel_unlock(original);
	ast_channel_unlock(clonechan);

	ao2_link(channels, clonechan);
	ao2_link(channels, original);
	ao2_unlock(channels);

	/* Release our held safety references. */
	ast_channel_unref(original);
	ast_channel_unref(clonechan);

	ao2_cleanup(rformat);
	ao2_cleanup(wformat);
}

void ast_set_callerid(struct ast_channel *chan, const char *cid_num, const char *cid_name, const char *cid_ani)
{
	ast_channel_lock(chan);

	if (cid_num) {
		ast_channel_caller(chan)->id.number.valid = 1;
		ast_free(ast_channel_caller(chan)->id.number.str);
		ast_channel_caller(chan)->id.number.str = ast_strdup(cid_num);
	}
	if (cid_name) {
		ast_channel_caller(chan)->id.name.valid = 1;
		ast_free(ast_channel_caller(chan)->id.name.str);
		ast_channel_caller(chan)->id.name.str = ast_strdup(cid_name);
	}
	if (cid_ani) {
		ast_channel_caller(chan)->ani.number.valid = 1;
		ast_free(ast_channel_caller(chan)->ani.number.str);
		ast_channel_caller(chan)->ani.number.str = ast_strdup(cid_ani);
	}

	ast_channel_publish_snapshot(chan);

	ast_channel_unlock(chan);
}

void ast_channel_set_caller(struct ast_channel *chan, const struct ast_party_caller *caller, const struct ast_set_party_caller *update)
{
	if (ast_channel_caller(chan) == caller) {
		/* Don't set to self */
		return;
	}

	ast_channel_lock(chan);
	ast_party_caller_set(ast_channel_caller(chan), caller, update);
	ast_channel_unlock(chan);
}

void ast_channel_set_caller_event(struct ast_channel *chan, const struct ast_party_caller *caller, const struct ast_set_party_caller *update)
{
	if (ast_channel_caller(chan) == caller) {
		/* Don't set to self */
		return;
	}

	ast_channel_lock(chan);
	ast_party_caller_set(ast_channel_caller(chan), caller, update);
	ast_channel_publish_snapshot(chan);
	ast_channel_unlock(chan);
}

int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
{
	int oldstate = ast_channel_state(chan);
	char name[AST_CHANNEL_NAME], *dashptr;

	if (oldstate == state)
		return 0;

	ast_copy_string(name, ast_channel_name(chan), sizeof(name));
	if ((dashptr = strrchr(name, '-'))) {
		*dashptr = '\0';
	}

	ast_channel_state_set(chan, state);

	ast_publish_channel_state(chan);

	/* We have to pass AST_DEVICE_UNKNOWN here because it is entirely possible that the channel driver
	 * for this channel is using the callback method for device state. If we pass in an actual state here
	 * we override what they are saying the state is and things go amuck. */
	ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, (ast_test_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_DEVSTATE_CACHE) ? AST_DEVSTATE_NOT_CACHABLE : AST_DEVSTATE_CACHABLE), name);

	return 0;
}

/*! \brief Bridge two channels together (early) */
int ast_channel_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
{
	/* Make sure we can early bridge, if not error out */
	if (!ast_channel_tech(c0)->early_bridge || (c1 && (!ast_channel_tech(c1)->early_bridge || ast_channel_tech(c0)->early_bridge != ast_channel_tech(c1)->early_bridge)))
		return -1;

	return ast_channel_tech(c0)->early_bridge(c0, c1);
}

/*! \brief Sets an option on a channel */
int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
{
	int res;

	ast_channel_lock(chan);
	if (!ast_channel_tech(chan)->setoption) {
		errno = ENOSYS;
		ast_channel_unlock(chan);
		return -1;
	}

	if (block)
		ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");

	res = ast_channel_tech(chan)->setoption(chan, option, data, datalen);
	ast_channel_unlock(chan);

	return res;
}

int ast_channel_queryoption(struct ast_channel *chan, int option, void *data, int *datalen, int block)
{
	int res;

	ast_channel_lock(chan);
	if (!ast_channel_tech(chan)->queryoption) {
		errno = ENOSYS;
		ast_channel_unlock(chan);
		return -1;
	}

	if (block)
		ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");

	res = ast_channel_tech(chan)->queryoption(chan, option, data, datalen);
	ast_channel_unlock(chan);

	return res;
}

struct tonepair_def {
	int freq1;
	int freq2;
	int duration;
	int vol;
};

struct tonepair_state {
	int fac1;
	int fac2;
	int v1_1;
	int v2_1;
	int v3_1;
	int v1_2;
	int v2_2;
	int v3_2;
	struct ast_format *origwfmt;
	int pos;
	int duration;
	int modulate;
	struct ast_frame f;
	unsigned char offset[AST_FRIENDLY_OFFSET];
	short data[4000];
};

static void tonepair_release(struct ast_channel *chan, void *params)
{
	struct tonepair_state *ts = params;

	if (chan) {
		ast_set_write_format(chan, ts->origwfmt);
	}
	ao2_cleanup(ts->origwfmt);
	ast_free(ts);
}

static void *tonepair_alloc(struct ast_channel *chan, void *params)
{
	struct tonepair_state *ts;
	struct tonepair_def *td = params;

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

	ts->origwfmt = ao2_bump(ast_channel_writeformat(chan));
	if (ast_set_write_format(chan, ast_format_slin)) {
		ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", ast_channel_name(chan));
		tonepair_release(NULL, ts);
		ts = NULL;
	} else {
		ts->fac1 = 2.0 * cos(2.0 * M_PI * (td->freq1 / 8000.0)) * 32768.0;
		ts->v1_1 = 0;
		ts->v2_1 = sin(-4.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
		ts->v3_1 = sin(-2.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
		ts->v2_1 = 0;
		ts->fac2 = 2.0 * cos(2.0 * M_PI * (td->freq2 / 8000.0)) * 32768.0;
		ts->v2_2 = sin(-4.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
		ts->v3_2 = sin(-2.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
		ts->duration = td->duration;
		ts->modulate = 0;
	}
	/* Let interrupts interrupt :) */
	ast_set_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
	return ts;
}

static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
{
	struct tonepair_state *ts = data;
	int x;

	/* we need to prepare a frame with 16 * timelen samples as we're
	 * generating SLIN audio
	 */
	len = samples * 2;

	if (len > sizeof(ts->data) / 2 - 1) {
		ast_log(LOG_WARNING, "Can't generate that much data!\n");
		return -1;
	}
	memset(&ts->f, 0, sizeof(ts->f));
	for (x=0;x<len/2;x++) {
		ts->v1_1 = ts->v2_1;
		ts->v2_1 = ts->v3_1;
		ts->v3_1 = (ts->fac1 * ts->v2_1 >> 15) - ts->v1_1;

		ts->v1_2 = ts->v2_2;
		ts->v2_2 = ts->v3_2;
		ts->v3_2 = (ts->fac2 * ts->v2_2 >> 15) - ts->v1_2;
		if (ts->modulate) {
			int p;
			p = ts->v3_2 - 32768;
			if (p < 0) p = -p;
			p = ((p * 9) / 10) + 1;
			ts->data[x] = (ts->v3_1 * p) >> 15;
		} else
			ts->data[x] = ts->v3_1 + ts->v3_2;
	}
	ts->f.frametype = AST_FRAME_VOICE;
	ts->f.subclass.format = ast_format_slin;
	ts->f.datalen = len;
	ts->f.samples = samples;
	ts->f.offset = AST_FRIENDLY_OFFSET;
	ts->f.data.ptr = ts->data;
	ast_write(chan, &ts->f);
	ts->pos += x;
	if (ts->duration > 0) {
		if (ts->pos >= ts->duration * 8)
			return -1;
	}
	return 0;
}

static struct ast_generator tonepair = {
	.alloc = tonepair_alloc,
	.release = tonepair_release,
	.generate = tonepair_generator,
};

int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
{
	struct tonepair_def d = { 0, };

	d.freq1 = freq1;
	d.freq2 = freq2;
	d.duration = duration;
	d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
	if (ast_activate_generator(chan, &tonepair, &d))
		return -1;
	return 0;
}

void ast_tonepair_stop(struct ast_channel *chan)
{
	ast_deactivate_generator(chan);
}

int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
{
	int res;

	if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
		return res;

	/* Give us some wiggle room */
	while (ast_channel_generatordata(chan) && ast_waitfor(chan, 100) >= 0) {
		struct ast_frame *f = ast_read(chan);
		if (f)
			ast_frfree(f);
		else
			return -1;
	}
	return 0;
}

ast_group_t ast_get_group(const char *s)
{
	char *piece;
	char *c;
	int start=0, finish=0, x;
	ast_group_t group = 0;

	if (ast_strlen_zero(s))
		return 0;

	c = ast_strdupa(s);

	while ((piece = strsep(&c, ","))) {
		if (sscanf(piece, "%30d-%30d", &start, &finish) == 2) {
			/* Range */
		} else if (sscanf(piece, "%30d", &start)) {
			/* Just one */
			finish = start;
		} else {
			ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
			continue;
		}
		for (x = start; x <= finish; x++) {
			if ((x > 63) || (x < 0)) {
				ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
			} else
				group |= ((ast_group_t) 1 << x);
		}
	}
	return group;
}

/*! \brief Named group member structure */
struct namedgroup_member {
	/*! Pre-built hash of group member name. */
	unsigned int hash;
	/*! Group member name. (End allocation of name string.) */
	char name[1];
};

/*! \brief Comparison function used for named group container */
static int namedgroup_cmp_cb(void *obj, void *arg, int flags)
{
	const struct namedgroup_member *an = obj;
	const struct namedgroup_member *bn = arg;

	return strcmp(an->name, bn->name) ? 0 : CMP_MATCH | CMP_STOP;
}

/*! \brief Hashing function used for named group container */
static int namedgroup_hash_cb(const void *obj, const int flags)
{
	const struct namedgroup_member *member = obj;

	return member->hash;
}

struct ast_namedgroups *ast_get_namedgroups(const char *s)
{
	struct ao2_container *namedgroups;
	char *piece;
	char *c;

	if (!s) {
		return NULL;
	}

	/*! \brief Remove leading and trailing whitespace */
	c = ast_trim_blanks(ast_strdupa(ast_skip_blanks(s)));
	if (ast_strlen_zero(c)) {
		return NULL;
	}

	namedgroups = ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_NOLOCK, 19,
		namedgroup_hash_cb, namedgroup_cmp_cb);
	if (!namedgroups) {
		return NULL;
	}

	while ((piece = strsep(&c, ","))) {
		struct namedgroup_member *member;
		size_t len;

		/* remove leading/trailing whitespace */
		piece = ast_strip(piece);

		len = strlen(piece);
		if (!len) {
			continue;
		}

		member = ao2_alloc_options(sizeof(*member) + len, NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
		if (!member) {
			ao2_ref(namedgroups, -1);
			return NULL;
		}
		strcpy(member->name, piece);/* Safe */
		member->hash = ast_str_hash(member->name);

		/* every group name may exist only once, delete duplicates */
		ao2_find(namedgroups, member, OBJ_POINTER | OBJ_UNLINK | OBJ_NODATA);
		ao2_link(namedgroups, member);
		ao2_ref(member, -1);
	}

	if (!ao2_container_count(namedgroups)) {
		/* There were no group names specified. */
		ao2_ref(namedgroups, -1);
		namedgroups = NULL;
	}

	return (struct ast_namedgroups *) namedgroups;
}

struct ast_namedgroups *ast_unref_namedgroups(struct ast_namedgroups *groups)
{
	ao2_cleanup(groups);
	return NULL;
}

struct ast_namedgroups *ast_ref_namedgroups(struct ast_namedgroups *groups)
{
	if (groups) {
		ao2_ref(groups, 1);
	}
	return groups;
}

static int (*ast_moh_start_ptr)(struct ast_channel *, const char *, const char *) = NULL;
static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;

void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *, const char *),
				 void (*stop_ptr)(struct ast_channel *),
				 void (*cleanup_ptr)(struct ast_channel *))
{
	ast_moh_start_ptr = start_ptr;
	ast_moh_stop_ptr = stop_ptr;
	ast_moh_cleanup_ptr = cleanup_ptr;
}

void ast_uninstall_music_functions(void)
{
	ast_moh_start_ptr = NULL;
	ast_moh_stop_ptr = NULL;
	ast_moh_cleanup_ptr = NULL;
}

int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
{
	if (ast_moh_start_ptr)
		return ast_moh_start_ptr(chan, mclass, interpclass);

	ast_verb(3, "Music class %s requested but no musiconhold loaded.\n", mclass ? mclass : (interpclass ? interpclass : "default"));

	return -1;
}

void ast_moh_stop(struct ast_channel *chan)
{
	if (ast_moh_stop_ptr)
		ast_moh_stop_ptr(chan);
}

void ast_moh_cleanup(struct ast_channel *chan)
{
	if (ast_moh_cleanup_ptr)
		ast_moh_cleanup_ptr(chan);
}

static int ast_channel_hash_cb(const void *obj, const int flags)
{
	const char *name = (flags & OBJ_KEY) ? obj : ast_channel_name((struct ast_channel *) obj);

	/* If the name isn't set, return 0 so that the ao2_find() search will
	 * start in the first bucket. */
	if (ast_strlen_zero(name)) {
		return 0;
	}

	return ast_str_case_hash(name);
}

/*!
 * \internal
 * \brief Print channel object key (name).
 * \since 12.0.0
 *
 * \param v_obj A pointer to the object we want the key printed.
 * \param where User data needed by prnt to determine where to put output.
 * \param prnt Print output callback function to use.
 *
 * \return Nothing
 */
static void prnt_channel_key(void *v_obj, void *where, ao2_prnt_fn *prnt)
{
	struct ast_channel *chan = v_obj;

	if (!chan) {
		return;
	}
	prnt(where, "%s", ast_channel_name(chan));
}

/*!
 * \brief List of channel variables to append to all channel-related events.
 */
struct manager_channel_variable {
	AST_LIST_ENTRY(manager_channel_variable) entry;
	unsigned int isfunc:1;
	char name[];
};

AST_RWLIST_HEAD(external_vars, manager_channel_variable);

static struct external_vars ami_vars;
static struct external_vars ari_vars;

static void free_external_channelvars(struct external_vars *channelvars)
{
	struct manager_channel_variable *var;
	AST_RWLIST_WRLOCK(channelvars);
	while ((var = AST_RWLIST_REMOVE_HEAD(channelvars, entry))) {
		ast_free(var);
	}
	AST_RWLIST_UNLOCK(channelvars);
}

static int channel_has_external_vars(struct external_vars *channelvars)
{
	int vars_present;

	AST_RWLIST_RDLOCK(channelvars);
	vars_present = !AST_LIST_EMPTY(channelvars);
	AST_RWLIST_UNLOCK(channelvars);

	return vars_present;
}

int ast_channel_has_manager_vars(void)
{
	return channel_has_external_vars(&ami_vars);
}

int ast_channel_has_ari_vars(void)
{
	return channel_has_external_vars(&ari_vars);
}

static void channel_set_external_vars(struct external_vars *channelvars, size_t varc, char **vars)
{
	size_t i;

	free_external_channelvars(channelvars);
	AST_RWLIST_WRLOCK(channelvars);
	for (i = 0; i < varc; ++i) {
		const char *var = vars[i];
		struct manager_channel_variable *mcv;
		if (!(mcv = ast_calloc(1, sizeof(*mcv) + strlen(var) + 1))) {
			break;
		}
		strcpy(mcv->name, var); /* SAFE */
		if (strchr(var, '(')) {
			mcv->isfunc = 1;
		}
		AST_RWLIST_INSERT_TAIL(channelvars, mcv, entry);
	}
	AST_RWLIST_UNLOCK(channelvars);

}

void ast_channel_set_manager_vars(size_t varc, char **vars)
{
	channel_set_external_vars(&ami_vars, varc, vars);
}

void ast_channel_set_ari_vars(size_t varc, char **vars)
{
	channel_set_external_vars(&ari_vars, varc, vars);
}

/*!
 * \brief Destructor for lists of variables.
 * \param obj AO2 object.
 */
static void varshead_dtor(void *obj)
{
	struct varshead *head = obj;
	struct ast_var_t *var;

	while ((var = AST_RWLIST_REMOVE_HEAD(head, entries))) {
		ast_var_delete(var);
	}
}

struct varshead *ast_channel_get_vars(struct ast_channel *chan)
{
	RAII_VAR(struct varshead *, ret, NULL, ao2_cleanup);
	struct ast_var_t *cv;

	ret = ao2_alloc(sizeof(*ret), varshead_dtor);

	if (!ret) {
		return NULL;
	}

	AST_LIST_TRAVERSE(ast_channel_varshead(chan), cv, entries) {
		struct ast_var_t *var = ast_var_assign(ast_var_name(cv), ast_var_value(cv));

		if (!var) {
			return NULL;
		}

		AST_LIST_INSERT_TAIL(ret, var, entries);
	}

	ao2_ref(ret, +1);
	return ret;
}

static struct varshead *channel_get_external_vars(struct external_vars *channelvars,
	struct ast_channel *chan)
{
	RAII_VAR(struct varshead *, ret, NULL, ao2_cleanup);
	RAII_VAR(struct ast_str *, tmp, NULL, ast_free);
	struct manager_channel_variable *mcv;
	SCOPED_LOCK(lock, channelvars, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);

	if (AST_LIST_EMPTY(channelvars)) {
		return NULL;
	}

	ret = ao2_alloc(sizeof(*ret), varshead_dtor);
	tmp = ast_str_create(16);

	if (!ret || !tmp) {
		return NULL;
	}

	AST_LIST_TRAVERSE(channelvars, mcv, entry) {
		const char *val = NULL;
		struct ast_var_t *var;

		if (mcv->isfunc) {
			if (ast_func_read2(chan, mcv->name, &tmp, 0) == 0) {
				val = ast_str_buffer(tmp);
			} else {
				ast_log(LOG_ERROR,
					"Error invoking function %s\n", mcv->name);
			}
		} else {
			val = pbx_builtin_getvar_helper(chan, mcv->name);
		}

		var = ast_var_assign(mcv->name, val ? val : "");
		if (!var) {
			return NULL;
		}

		AST_RWLIST_INSERT_TAIL(ret, var, entries);
	}

	ao2_ref(ret, +1);
	return ret;

}

struct varshead *ast_channel_get_manager_vars(struct ast_channel *chan)
{
	return channel_get_external_vars(&ami_vars, chan);
}

struct varshead *ast_channel_get_ari_vars(struct ast_channel *chan)
{
	return channel_get_external_vars(&ari_vars, chan);
}

static void channels_shutdown(void)
{
	free_external_channelvars(&ami_vars);
	free_external_channelvars(&ari_vars);

	ast_cli_unregister_multiple(cli_channel, ARRAY_LEN(cli_channel));
	if (channels) {
		ao2_container_unregister("channels");
		ao2_ref(channels, -1);
		channels = NULL;
	}
	ast_channel_unregister(&surrogate_tech);
}

int ast_channels_init(void)
{
	channels = ao2_container_alloc(NUM_CHANNEL_BUCKETS,
			ast_channel_hash_cb, ast_channel_cmp_cb);
	if (!channels) {
		return -1;
	}
	ao2_container_register("channels", channels, prnt_channel_key);

	ast_channel_register(&surrogate_tech);

	ast_stasis_channels_init();

	ast_cli_register_multiple(cli_channel, ARRAY_LEN(cli_channel));

	ast_register_cleanup(channels_shutdown);

	AST_RWLIST_HEAD_INIT(&ami_vars);
	AST_RWLIST_HEAD_INIT(&ari_vars);

	return 0;
}

/*! \brief Print call group and pickup group ---*/
char *ast_print_group(char *buf, int buflen, ast_group_t group)
{
	unsigned int i;
	int first = 1;
	char num[3];

	buf[0] = '\0';

	if (!group)	/* Return empty string if no group */
		return buf;

	for (i = 0; i <= 63; i++) {	/* Max group is 63 */
		if (group & ((ast_group_t) 1 << i)) {
			if (!first) {
				strncat(buf, ", ", buflen - strlen(buf) - 1);
			} else {
				first = 0;
			}
			snprintf(num, sizeof(num), "%u", i);
			strncat(buf, num, buflen - strlen(buf) - 1);
		}
	}
	return buf;
}

char *ast_print_namedgroups(struct ast_str **buf, struct ast_namedgroups *group)
{
	struct ao2_container *grp = (struct ao2_container *) group;
	struct namedgroup_member *ng;
	int first = 1;
	struct ao2_iterator it;

	if (!grp) {
		return ast_str_buffer(*buf);
	}

	for (it = ao2_iterator_init(grp, 0); (ng = ao2_iterator_next(&it)); ao2_ref(ng, -1)) {
		if (!first) {
			ast_str_append(buf, 0, ", ");
		} else {
			first = 0;
		}
		ast_str_append(buf, 0, "%s", ng->name);
	}
	ao2_iterator_destroy(&it);

	return ast_str_buffer(*buf);
}

static int namedgroup_match(void *obj, void *arg, int flags)
{
	void *match;

	match = ao2_find(arg, obj, OBJ_POINTER);
	ao2_cleanup(match);

	return match ? CMP_MATCH | CMP_STOP : 0;
}

int ast_namedgroups_intersect(struct ast_namedgroups *a, struct ast_namedgroups *b)
{
	void *match;
	struct ao2_container *group_a = (struct ao2_container *) a;
	struct ao2_container *group_b = (struct ao2_container *) b;

	if (!a || !b) {
		return 0;
	}

	/*
	 * Do groups a and b intersect?  Since a and b are hash tables,
	 * the average time complexity is:
	 * O(a.count <= b.count ? a.count : b.count)
	 */
	if (ao2_container_count(group_b) < ao2_container_count(group_a)) {
		/* Traverse over the smaller group. */
		SWAP(group_a, group_b);
	}
	match = ao2_callback(group_a, 0, namedgroup_match, group_b);
	ao2_cleanup(match);

	return match != NULL;
}

void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
{
	struct ast_variable *cur;

	for (cur = vars; cur; cur = cur->next) {
		pbx_builtin_setvar_helper(chan, cur->name, cur->value);
	}
}

static void *silence_generator_alloc(struct ast_channel *chan, void *data)
{
	/* just store the data pointer in the channel structure */
	return data;
}

static void silence_generator_release(struct ast_channel *chan, void *data)
{
	/* nothing to do */
}

static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
{
	short buf[samples];
	struct ast_frame frame = {
		.frametype = AST_FRAME_VOICE,
		.data.ptr = buf,
		.samples = samples,
		.datalen = sizeof(buf),
	};
	frame.subclass.format = ast_format_slin;

	memset(buf, 0, sizeof(buf));

	if (ast_write(chan, &frame))
		return -1;

	return 0;
}

static struct ast_generator silence_generator = {
	.alloc = silence_generator_alloc,
	.release = silence_generator_release,
	.generate = silence_generator_generate,
};

struct ast_silence_generator {
	struct ast_format *old_write_format;
};

struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
{
	struct ast_silence_generator *state;

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

	state->old_write_format = ao2_bump(ast_channel_writeformat(chan));

	if (ast_set_write_format(chan, ast_format_slin) < 0) {
		ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
		ast_free(state);
		return NULL;
	}

	ast_activate_generator(chan, &silence_generator, state);

	ast_debug(1, "Started silence generator on '%s'\n", ast_channel_name(chan));

	return state;
}

static int deactivate_silence_generator(struct ast_channel *chan)
{
	ast_channel_lock(chan);

	if (!ast_channel_generatordata(chan)) {
		ast_debug(1, "Trying to stop silence generator when there is no generator on '%s'\n",
			ast_channel_name(chan));
		ast_channel_unlock(chan);
		return 0;
	}
	if (ast_channel_generator(chan) != &silence_generator) {
		ast_debug(1, "Trying to stop silence generator when it is not the current generator on '%s'\n",
			ast_channel_name(chan));
		ast_channel_unlock(chan);
		return 0;
	}
	deactivate_generator_nolock(chan);

	ast_channel_unlock(chan);

	return 1;
}

void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
{
	if (!state) {
		return;
	}

	if (deactivate_silence_generator(chan)) {
		ast_debug(1, "Stopped silence generator on '%s'\n", ast_channel_name(chan));
		if (ast_set_write_format(chan, state->old_write_format) < 0) {
			ast_log(LOG_ERROR, "Could not return write format to its original state\n");
		}
	}
	ao2_cleanup(state->old_write_format);
	ast_free(state);
}


/*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
const char *channelreloadreason2txt(enum channelreloadreason reason)
{
	switch (reason) {
	case CHANNEL_MODULE_LOAD:
		return "LOAD (Channel module load)";

	case CHANNEL_MODULE_RELOAD:
		return "RELOAD (Channel module reload)";

	case CHANNEL_CLI_RELOAD:
		return "CLIRELOAD (Channel module reload by CLI command)";

	default:
		return "MANAGERRELOAD (Channel module reload by manager)";
	}
};

/*
 * Wrappers for various ast_say_*() functions that call the full version
 * of the same functions.
 * The proper place would be say.c, but that file is optional and one
 * must be able to build asterisk even without it (using a loadable 'say'
 * implementation that only supplies the 'full' version of the functions.
 */

int ast_say_number(struct ast_channel *chan, int num,
	const char *ints, const char *language, const char *options)
{
	return ast_say_number_full(chan, num, ints, language, options, -1, -1);
}

int ast_say_enumeration(struct ast_channel *chan, int num,
	const char *ints, const char *language, const char *options)
{
	return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
}

int ast_say_digits(struct ast_channel *chan, int num,
	const char *ints, const char *lang)
{
	return ast_say_digits_full(chan, num, ints, lang, -1, -1);
}

int ast_say_digit_str(struct ast_channel *chan, const char *str,
	const char *ints, const char *lang)
{
	return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
}

int ast_say_character_str(struct ast_channel *chan, const char *str,
	const char *ints, const char *lang, enum ast_say_case_sensitivity sensitivity)
{
	return ast_say_character_str_full(chan, str, ints, lang, sensitivity, -1, -1);
}

int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
	const char *ints, const char *lang)
{
	return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
}

int ast_say_digits_full(struct ast_channel *chan, int num,
	const char *ints, const char *lang, int audiofd, int ctrlfd)
{
	char buf[256];

	snprintf(buf, sizeof(buf), "%d", num);

	return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);
}

void ast_connected_line_copy_from_caller(struct ast_party_connected_line *dest, const struct ast_party_caller *src)
{
	ast_party_id_copy(&dest->id, &src->id);
	ast_party_id_copy(&dest->ani, &src->ani);
	dest->ani2 = src->ani2;
}

void ast_connected_line_copy_to_caller(struct ast_party_caller *dest, const struct ast_party_connected_line *src)
{
	ast_party_id_copy(&dest->id, &src->id);
	ast_party_id_copy(&dest->ani, &src->ani);

	dest->ani2 = src->ani2;
}

void ast_channel_set_connected_line(struct ast_channel *chan, const struct ast_party_connected_line *connected, const struct ast_set_party_connected_line *update)
{
	if (ast_channel_connected(chan) == connected) {
		/* Don't set to self */
		return;
	}

	ast_channel_lock(chan);
	ast_party_connected_line_set(ast_channel_connected(chan), connected, update);
	ast_channel_publish_snapshot(chan);
	ast_channel_unlock(chan);
}

/*! \note Should follow struct ast_party_name */
struct ast_party_name_ies {
	/*! \brief Subscriber name ie */
	int str;
	/*! \brief Character set ie. */
	int char_set;
	/*! \brief presentation-indicator ie */
	int presentation;
	/*! \brief valid/present ie */
	int valid;
};

/*!
 * \internal
 * \since 1.8
 * \brief Build a party name information data frame component.
 *
 * \param data Buffer to fill with the frame data
 * \param datalen Size of the buffer to fill
 * \param name Party name information
 * \param label Name of particular party name
 * \param ies Data frame ie values for the party name components
 *
 * \retval -1 if error
 * \retval Amount of data buffer used
 */
static int party_name_build_data(unsigned char *data, size_t datalen, const struct ast_party_name *name, const char *label, const struct ast_party_name_ies *ies)
{
	size_t length;
	size_t pos = 0;

	/*
	 * The size of integer values must be fixed in case the frame is
	 * shipped to another machine.
	 */
	if (name->str) {
		length = strlen(name->str);
		if (datalen < pos + (sizeof(data[0]) * 2) + length) {
			ast_log(LOG_WARNING, "No space left for %s name\n", label);
			return -1;
		}
		data[pos++] = ies->str;
		data[pos++] = length;
		memcpy(data + pos, name->str, length);
		pos += length;
	}

	if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
		ast_log(LOG_WARNING, "No space left for %s name char set\n", label);
		return -1;
	}
	data[pos++] = ies->char_set;
	data[pos++] = 1;
	data[pos++] = name->char_set;

	if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
		ast_log(LOG_WARNING, "No space left for %s name presentation\n", label);
		return -1;
	}
	data[pos++] = ies->presentation;
	data[pos++] = 1;
	data[pos++] = name->presentation;

	if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
		ast_log(LOG_WARNING, "No space left for %s name valid\n", label);
		return -1;
	}
	data[pos++] = ies->valid;
	data[pos++] = 1;
	data[pos++] = name->valid;

	return pos;
}

/*! \note Should follow struct ast_party_number */
struct ast_party_number_ies {
	/*! \brief Subscriber phone number ie */
	int str;
	/*! \brief Type-Of-Number and Numbering-Plan ie */
	int plan;
	/*! \brief presentation-indicator ie */
	int presentation;
	/*! \brief valid/present ie */
	int valid;
};

/*!
 * \internal
 * \since 1.8
 * \brief Build a party number information data frame component.
 *
 * \param data Buffer to fill with the frame data
 * \param datalen Size of the buffer to fill
 * \param number Party number information
 * \param label Name of particular party number
 * \param ies Data frame ie values for the party number components
 *
 * \retval -1 if error
 * \retval Amount of data buffer used
 */
static int party_number_build_data(unsigned char *data, size_t datalen, const struct ast_party_number *number, const char *label, const struct ast_party_number_ies *ies)
{
	size_t length;
	size_t pos = 0;

	/*
	 * The size of integer values must be fixed in case the frame is
	 * shipped to another machine.
	 */
	if (number->str) {
		length = strlen(number->str);
		if (datalen < pos + (sizeof(data[0]) * 2) + length) {
			ast_log(LOG_WARNING, "No space left for %s number\n", label);
			return -1;
		}
		data[pos++] = ies->str;
		data[pos++] = length;
		memcpy(data + pos, number->str, length);
		pos += length;
	}

	if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
		ast_log(LOG_WARNING, "No space left for %s numbering plan\n", label);
		return -1;
	}
	data[pos++] = ies->plan;
	data[pos++] = 1;
	data[pos++] = number->plan;

	if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
		ast_log(LOG_WARNING, "No space left for %s number presentation\n", label);
		return -1;
	}
	data[pos++] = ies->presentation;
	data[pos++] = 1;
	data[pos++] = number->presentation;

	if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
		ast_log(LOG_WARNING, "No space left for %s number valid\n", label);
		return -1;
	}
	data[pos++] = ies->valid;
	data[pos++] = 1;
	data[pos++] = number->valid;

	return pos;
}

/*! \note Should follow struct ast_party_subaddress */
struct ast_party_subaddress_ies {
	/*! \brief subaddress ie. */
	int str;
	/*! \brief subaddress type ie */
	int type;
	/*! \brief odd/even indicator ie */
	int odd_even_indicator;
	/*! \brief valid/present ie */
	int valid;
};

/*!
 * \internal
 * \since 1.8
 * \brief Build a party subaddress information data frame component.
 *
 * \param data Buffer to fill with the frame data
 * \param datalen Size of the buffer to fill
 * \param subaddress Party subaddress information
 * \param label Name of particular party subaddress
 * \param ies Data frame ie values for the party subaddress components
 *
 * \retval -1 if error
 * \retval Amount of data buffer used
 */
static int party_subaddress_build_data(unsigned char *data, size_t datalen, const struct ast_party_subaddress *subaddress, const char *label, const struct ast_party_subaddress_ies *ies)
{
	size_t length;
	size_t pos = 0;

	/*
	 * The size of integer values must be fixed in case the frame is
	 * shipped to another machine.
	 */
	if (subaddress->str) {
		length = strlen(subaddress->str);
		if (datalen < pos + (sizeof(data[0]) * 2) + length) {
			ast_log(LOG_WARNING, "No space left for %s subaddress\n", label);
			return -1;
		}
		data[pos++] = ies->str;
		data[pos++] = length;
		memcpy(data + pos, subaddress->str, length);
		pos += length;
	}

	if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
		ast_log(LOG_WARNING, "No space left for %s type of subaddress\n", label);
		return -1;
	}
	data[pos++] = ies->type;
	data[pos++] = 1;
	data[pos++] = subaddress->type;

	if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
		ast_log(LOG_WARNING,
			"No space left for %s subaddress odd-even indicator\n", label);
		return -1;
	}
	data[pos++] = ies->odd_even_indicator;
	data[pos++] = 1;
	data[pos++] = subaddress->odd_even_indicator;

	if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
		ast_log(LOG_WARNING, "No space left for %s subaddress valid\n", label);
		return -1;
	}
	data[pos++] = ies->valid;
	data[pos++] = 1;
	data[pos++] = subaddress->valid;

	return pos;
}

/*! \note Should follow struct ast_party_id */
struct ast_party_id_ies {
	/*! \brief Subscriber name ies */
	struct ast_party_name_ies name;
	/*! \brief Subscriber phone number ies */
	struct ast_party_number_ies number;
	/*! \brief Subscriber subaddress ies. */
	struct ast_party_subaddress_ies subaddress;
	/*! \brief User party id tag ie. */
	int tag;
	/*!
	 * \brief Combined name and number presentation ie.
	 * \note Not sent if value is zero.
	 */
	int combined_presentation;
};

/*!
 * \internal
 * \since 1.8
 * \brief Build a party id information data frame component.
 *
 * \param data Buffer to fill with the frame data
 * \param datalen Size of the buffer to fill
 * \param id Party id information
 * \param label Name of particular party id
 * \param ies Data frame ie values for the party id components
 * \param update What id information to build.  NULL if all.
 *
 * \retval -1 if error
 * \retval Amount of data buffer used
 */
static int party_id_build_data(unsigned char *data, size_t datalen,
	const struct ast_party_id *id, const char *label, const struct ast_party_id_ies *ies,
	const struct ast_set_party_id *update)
{
	size_t length;
	size_t pos = 0;
	int res;

	/*
	 * The size of integer values must be fixed in case the frame is
	 * shipped to another machine.
	 */

	if (!update || update->name) {
		res = party_name_build_data(data + pos, datalen - pos, &id->name, label,
			&ies->name);
		if (res < 0) {
			return -1;
		}
		pos += res;
	}

	if (!update || update->number) {
		res = party_number_build_data(data + pos, datalen - pos, &id->number, label,
			&ies->number);
		if (res < 0) {
			return -1;
		}
		pos += res;
	}

	if (!update || update->subaddress) {
		res = party_subaddress_build_data(data + pos, datalen - pos, &id->subaddress,
			label, &ies->subaddress);
		if (res < 0) {
			return -1;
		}
		pos += res;
	}

	/* *************** Party id user tag **************************** */
	if (id->tag) {
		length = strlen(id->tag);
		if (datalen < pos + (sizeof(data[0]) * 2) + length) {
			ast_log(LOG_WARNING, "No space left for %s tag\n", label);
			return -1;
		}
		data[pos++] = ies->tag;
		data[pos++] = length;
		memcpy(data + pos, id->tag, length);
		pos += length;
	}

	/* *************** Party id combined presentation *************** */
	if (ies->combined_presentation && (!update || update->number)) {
		int presentation;

		if (!update || update->name) {
			presentation = ast_party_id_presentation(id);
		} else {
			/*
			 * We must compromise because not all the information is available
			 * to determine a combined presentation value.
			 * We will only send the number presentation instead.
			 */
			presentation = id->number.presentation;
		}

		if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
			ast_log(LOG_WARNING, "No space left for %s combined presentation\n", label);
			return -1;
		}
		data[pos++] = ies->combined_presentation;
		data[pos++] = 1;
		data[pos++] = presentation;
	}

	return pos;
}

/*!
 * \brief Element identifiers for connected line indication frame data
 * \note Only add to the end of this enum.
 */
enum {
	AST_CONNECTED_LINE_NUMBER,
	AST_CONNECTED_LINE_NAME,
	AST_CONNECTED_LINE_NUMBER_PLAN,
	AST_CONNECTED_LINE_ID_PRESENTATION,/* Combined number and name presentation. */
	AST_CONNECTED_LINE_SOURCE,
	AST_CONNECTED_LINE_SUBADDRESS,
	AST_CONNECTED_LINE_SUBADDRESS_TYPE,
	AST_CONNECTED_LINE_SUBADDRESS_ODD_EVEN,
	AST_CONNECTED_LINE_SUBADDRESS_VALID,
	AST_CONNECTED_LINE_TAG,
	AST_CONNECTED_LINE_VERSION,
	/*
	 * No more party id combined number and name presentation values
	 * need to be created.
	 */
	AST_CONNECTED_LINE_NAME_VALID,
	AST_CONNECTED_LINE_NAME_CHAR_SET,
	AST_CONNECTED_LINE_NAME_PRESENTATION,
	AST_CONNECTED_LINE_NUMBER_VALID,
	AST_CONNECTED_LINE_NUMBER_PRESENTATION,
	AST_CONNECTED_LINE_PRIV_NUMBER,
	AST_CONNECTED_LINE_PRIV_NUMBER_PLAN,
	AST_CONNECTED_LINE_PRIV_NUMBER_VALID,
	AST_CONNECTED_LINE_PRIV_NUMBER_PRESENTATION,
	AST_CONNECTED_LINE_PRIV_NAME,
	AST_CONNECTED_LINE_PRIV_NAME_VALID,
	AST_CONNECTED_LINE_PRIV_NAME_CHAR_SET,
	AST_CONNECTED_LINE_PRIV_NAME_PRESENTATION,
	AST_CONNECTED_LINE_PRIV_SUBADDRESS,
	AST_CONNECTED_LINE_PRIV_SUBADDRESS_TYPE,
	AST_CONNECTED_LINE_PRIV_SUBADDRESS_ODD_EVEN,
	AST_CONNECTED_LINE_PRIV_SUBADDRESS_VALID,
	AST_CONNECTED_LINE_PRIV_TAG,
};

int ast_connected_line_build_data(unsigned char *data, size_t datalen, const struct ast_party_connected_line *connected, const struct ast_set_party_connected_line *update)
{
	int32_t value;
	size_t pos = 0;
	int res;

	static const struct ast_party_id_ies ies = {
		.name.str = AST_CONNECTED_LINE_NAME,
		.name.char_set = AST_CONNECTED_LINE_NAME_CHAR_SET,
		.name.presentation = AST_CONNECTED_LINE_NAME_PRESENTATION,
		.name.valid = AST_CONNECTED_LINE_NAME_VALID,

		.number.str = AST_CONNECTED_LINE_NUMBER,
		.number.plan = AST_CONNECTED_LINE_NUMBER_PLAN,
		.number.presentation = AST_CONNECTED_LINE_NUMBER_PRESENTATION,
		.number.valid = AST_CONNECTED_LINE_NUMBER_VALID,

		.subaddress.str = AST_CONNECTED_LINE_SUBADDRESS,
		.subaddress.type = AST_CONNECTED_LINE_SUBADDRESS_TYPE,
		.subaddress.odd_even_indicator = AST_CONNECTED_LINE_SUBADDRESS_ODD_EVEN,
		.subaddress.valid = AST_CONNECTED_LINE_SUBADDRESS_VALID,

		.tag = AST_CONNECTED_LINE_TAG,
		.combined_presentation = AST_CONNECTED_LINE_ID_PRESENTATION,
	};

	static const struct ast_party_id_ies priv_ies = {
		.name.str = AST_CONNECTED_LINE_PRIV_NAME,
		.name.char_set = AST_CONNECTED_LINE_PRIV_NAME_CHAR_SET,
		.name.presentation = AST_CONNECTED_LINE_PRIV_NAME_PRESENTATION,
		.name.valid = AST_CONNECTED_LINE_PRIV_NAME_VALID,

		.number.str = AST_CONNECTED_LINE_PRIV_NUMBER,
		.number.plan = AST_CONNECTED_LINE_PRIV_NUMBER_PLAN,
		.number.presentation = AST_CONNECTED_LINE_PRIV_NUMBER_PRESENTATION,
		.number.valid = AST_CONNECTED_LINE_PRIV_NUMBER_VALID,

		.subaddress.str = AST_CONNECTED_LINE_PRIV_SUBADDRESS,
		.subaddress.type = AST_CONNECTED_LINE_PRIV_SUBADDRESS_TYPE,
		.subaddress.odd_even_indicator = AST_CONNECTED_LINE_PRIV_SUBADDRESS_ODD_EVEN,
		.subaddress.valid = AST_CONNECTED_LINE_PRIV_SUBADDRESS_VALID,

		.tag = AST_CONNECTED_LINE_PRIV_TAG,
		.combined_presentation = 0,/* Not sent. */
	};

	/*
	 * The size of integer values must be fixed in case the frame is
	 * shipped to another machine.
	 */

	/* Connected line frame version */
	if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
		ast_log(LOG_WARNING, "No space left for connected line frame version\n");
		return -1;
	}
	data[pos++] = AST_CONNECTED_LINE_VERSION;
	data[pos++] = 1;
	data[pos++] = 2;/* Version 1 did not have a version ie */

	res = party_id_build_data(data + pos, datalen - pos, &connected->id,
		"connected line", &ies, update ? &update->id : NULL);
	if (res < 0) {
		return -1;
	}
	pos += res;

	res = party_id_build_data(data + pos, datalen - pos, &connected->priv,
		"connected line priv", &priv_ies, update ? &update->priv : NULL);
	if (res < 0) {
		return -1;
	}
	pos += res;

	/* Connected line source */
	if (datalen < pos + (sizeof(data[0]) * 2) + sizeof(value)) {
		ast_log(LOG_WARNING, "No space left for connected line source\n");
		return -1;
	}
	data[pos++] = AST_CONNECTED_LINE_SOURCE;
	data[pos++] = sizeof(value);
	value = htonl(connected->source);
	memcpy(data + pos, &value, sizeof(value));
	pos += sizeof(value);

	return pos;
}

int ast_connected_line_parse_data(const unsigned char *data, size_t datalen, struct ast_party_connected_line *connected)
{
	size_t pos;
	unsigned char ie_len;
	unsigned char ie_id;
	int32_t value;
	int frame_version = 1;
	int combined_presentation = 0;
	int got_combined_presentation = 0;/* TRUE if got a combined name and number presentation value. */

	for (pos = 0; pos < datalen; pos += ie_len) {
		if (datalen < pos + sizeof(ie_id) + sizeof(ie_len)) {
			ast_log(LOG_WARNING, "Invalid connected line update\n");
			return -1;
		}
		ie_id = data[pos++];
		ie_len = data[pos++];
		if (datalen < pos + ie_len) {
			ast_log(LOG_WARNING, "Invalid connected line update\n");
			return -1;
		}

		switch (ie_id) {
/* Connected line party frame version */
		case AST_CONNECTED_LINE_VERSION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line frame version (%u)\n",
					(unsigned) ie_len);
				break;
			}
			frame_version = data[pos];
			break;
/* Connected line party id name */
		case AST_CONNECTED_LINE_NAME:
			ast_free(connected->id.name.str);
			connected->id.name.str = ast_malloc(ie_len + 1);
			if (connected->id.name.str) {
				memcpy(connected->id.name.str, data + pos, ie_len);
				connected->id.name.str[ie_len] = 0;
			}
			break;
		case AST_CONNECTED_LINE_NAME_CHAR_SET:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line name char set (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->id.name.char_set = data[pos];
			break;
		case AST_CONNECTED_LINE_NAME_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line name presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->id.name.presentation = data[pos];
			break;
		case AST_CONNECTED_LINE_NAME_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line name valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->id.name.valid = data[pos];
			break;
/* Connected line party id number */
		case AST_CONNECTED_LINE_NUMBER:
			ast_free(connected->id.number.str);
			connected->id.number.str = ast_malloc(ie_len + 1);
			if (connected->id.number.str) {
				memcpy(connected->id.number.str, data + pos, ie_len);
				connected->id.number.str[ie_len] = 0;
			}
			break;
		case AST_CONNECTED_LINE_NUMBER_PLAN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line numbering plan (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->id.number.plan = data[pos];
			break;
		case AST_CONNECTED_LINE_NUMBER_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line number presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->id.number.presentation = data[pos];
			break;
		case AST_CONNECTED_LINE_NUMBER_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line number valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->id.number.valid = data[pos];
			break;
/* Connected line party id subaddress */
		case AST_CONNECTED_LINE_SUBADDRESS:
			ast_free(connected->id.subaddress.str);
			connected->id.subaddress.str = ast_malloc(ie_len + 1);
			if (connected->id.subaddress.str) {
				memcpy(connected->id.subaddress.str, data + pos, ie_len);
				connected->id.subaddress.str[ie_len] = 0;
			}
			break;
		case AST_CONNECTED_LINE_SUBADDRESS_TYPE:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line type of subaddress (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->id.subaddress.type = data[pos];
			break;
		case AST_CONNECTED_LINE_SUBADDRESS_ODD_EVEN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING,
					"Invalid connected line subaddress odd-even indicator (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->id.subaddress.odd_even_indicator = data[pos];
			break;
		case AST_CONNECTED_LINE_SUBADDRESS_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line subaddress valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->id.subaddress.valid = data[pos];
			break;
/* Connected line party tag */
		case AST_CONNECTED_LINE_TAG:
			ast_free(connected->id.tag);
			connected->id.tag = ast_malloc(ie_len + 1);
			if (connected->id.tag) {
				memcpy(connected->id.tag, data + pos, ie_len);
				connected->id.tag[ie_len] = 0;
			}
			break;
/* Connected line party id combined presentation */
		case AST_CONNECTED_LINE_ID_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line combined presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			combined_presentation = data[pos];
			got_combined_presentation = 1;
			break;
/* Private connected line party id name */
		case AST_CONNECTED_LINE_PRIV_NAME:
			ast_free(connected->priv.name.str);
			connected->priv.name.str = ast_malloc(ie_len + 1);
			if (connected->priv.name.str) {
				memcpy(connected->priv.name.str, data + pos, ie_len);
				connected->priv.name.str[ie_len] = 0;
			}
			break;
		case AST_CONNECTED_LINE_PRIV_NAME_CHAR_SET:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line private name char set (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->priv.name.char_set = data[pos];
			break;
		case AST_CONNECTED_LINE_PRIV_NAME_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line private name presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->priv.name.presentation = data[pos];
			break;
		case AST_CONNECTED_LINE_PRIV_NAME_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line private name valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->priv.name.valid = data[pos];
			break;
/* Private connected line party id number */
		case AST_CONNECTED_LINE_PRIV_NUMBER:
			ast_free(connected->priv.number.str);
			connected->priv.number.str = ast_malloc(ie_len + 1);
			if (connected->priv.number.str) {
				memcpy(connected->priv.number.str, data + pos, ie_len);
				connected->priv.number.str[ie_len] = 0;
			}
			break;
		case AST_CONNECTED_LINE_PRIV_NUMBER_PLAN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line private numbering plan (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->priv.number.plan = data[pos];
			break;
		case AST_CONNECTED_LINE_PRIV_NUMBER_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line private number presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->priv.number.presentation = data[pos];
			break;
		case AST_CONNECTED_LINE_PRIV_NUMBER_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line private number valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->priv.number.valid = data[pos];
			break;
/* Private connected line party id subaddress */
		case AST_CONNECTED_LINE_PRIV_SUBADDRESS:
			ast_free(connected->priv.subaddress.str);
			connected->priv.subaddress.str = ast_malloc(ie_len + 1);
			if (connected->priv.subaddress.str) {
				memcpy(connected->priv.subaddress.str, data + pos, ie_len);
				connected->priv.subaddress.str[ie_len] = 0;
			}
			break;
		case AST_CONNECTED_LINE_PRIV_SUBADDRESS_TYPE:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line private type of subaddress (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->priv.subaddress.type = data[pos];
			break;
		case AST_CONNECTED_LINE_PRIV_SUBADDRESS_ODD_EVEN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING,
					"Invalid connected line private subaddress odd-even indicator (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->priv.subaddress.odd_even_indicator = data[pos];
			break;
		case AST_CONNECTED_LINE_PRIV_SUBADDRESS_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid connected line private subaddress valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			connected->priv.subaddress.valid = data[pos];
			break;
/* Private connected line party tag */
		case AST_CONNECTED_LINE_PRIV_TAG:
			ast_free(connected->priv.tag);
			connected->priv.tag = ast_malloc(ie_len + 1);
			if (connected->priv.tag) {
				memcpy(connected->priv.tag, data + pos, ie_len);
				connected->priv.tag[ie_len] = 0;
			}
			break;
/* Connected line party source */
		case AST_CONNECTED_LINE_SOURCE:
			if (ie_len != sizeof(value)) {
				ast_log(LOG_WARNING, "Invalid connected line source (%u)\n",
					(unsigned) ie_len);
				break;
			}
			memcpy(&value, data + pos, sizeof(value));
			connected->source = ntohl(value);
			break;
/* Connected line party unknown element */
		default:
			ast_debug(1, "Unknown connected line element: %u (%u)\n",
				(unsigned) ie_id, (unsigned) ie_len);
			break;
		}
	}

	switch (frame_version) {
	case 1:
		/*
		 * The other end is an earlier version that we need to adjust
		 * for compatibility.
		 */
		connected->id.name.valid = 1;
		connected->id.name.char_set = AST_PARTY_CHAR_SET_ISO8859_1;
		connected->id.number.valid = 1;
		if (got_combined_presentation) {
			connected->id.name.presentation = combined_presentation;
			connected->id.number.presentation = combined_presentation;
		}
		break;
	case 2:
		/* The other end is at the same level as we are. */
		break;
	default:
		/*
		 * The other end is newer than we are.
		 * We need to assume that they are compatible with us.
		 */
		ast_debug(1, "Connected line frame has newer version: %u\n",
			(unsigned) frame_version);
		break;
	}

	return 0;
}

void ast_channel_update_connected_line(struct ast_channel *chan, const struct ast_party_connected_line *connected, const struct ast_set_party_connected_line *update)
{
	unsigned char data[1024];	/* This should be large enough */
	size_t datalen;

	datalen = ast_connected_line_build_data(data, sizeof(data), connected, update);
	if (datalen == (size_t) -1) {
		return;
	}

	ast_indicate_data(chan, AST_CONTROL_CONNECTED_LINE, data, datalen);
}

void ast_channel_queue_connected_line_update(struct ast_channel *chan, const struct ast_party_connected_line *connected, const struct ast_set_party_connected_line *update)
{
	unsigned char data[1024];	/* This should be large enough */
	size_t datalen;

	datalen = ast_connected_line_build_data(data, sizeof(data), connected, update);
	if (datalen == (size_t) -1) {
		return;
	}

	ast_queue_control_data(chan, AST_CONTROL_CONNECTED_LINE, data, datalen);
}

void ast_channel_set_redirecting(struct ast_channel *chan, const struct ast_party_redirecting *redirecting, const struct ast_set_party_redirecting *update)
{
	if (ast_channel_redirecting(chan) == redirecting) {
		/* Don't set to self */
		return;
	}

	ast_channel_lock(chan);
	ast_party_redirecting_set(ast_channel_redirecting(chan), redirecting, update);
	ast_channel_unlock(chan);
}

/*!
 * \brief Element identifiers for redirecting indication frame data
 * \note Only add to the end of this enum.
 */
enum {
	AST_REDIRECTING_FROM_NUMBER,
	AST_REDIRECTING_FROM_NAME,
	AST_REDIRECTING_FROM_NUMBER_PLAN,
	AST_REDIRECTING_FROM_ID_PRESENTATION,/* Combined number and name presentation. */
	AST_REDIRECTING_TO_NUMBER,
	AST_REDIRECTING_TO_NAME,
	AST_REDIRECTING_TO_NUMBER_PLAN,
	AST_REDIRECTING_TO_ID_PRESENTATION,/* Combined number and name presentation. */
	AST_REDIRECTING_REASON_CODE,
	AST_REDIRECTING_COUNT,
	AST_REDIRECTING_FROM_SUBADDRESS,
	AST_REDIRECTING_FROM_SUBADDRESS_TYPE,
	AST_REDIRECTING_FROM_SUBADDRESS_ODD_EVEN,
	AST_REDIRECTING_FROM_SUBADDRESS_VALID,
	AST_REDIRECTING_TO_SUBADDRESS,
	AST_REDIRECTING_TO_SUBADDRESS_TYPE,
	AST_REDIRECTING_TO_SUBADDRESS_ODD_EVEN,
	AST_REDIRECTING_TO_SUBADDRESS_VALID,
	AST_REDIRECTING_FROM_TAG,
	AST_REDIRECTING_TO_TAG,
	AST_REDIRECTING_VERSION,
	/*
	 * No more party id combined number and name presentation values
	 * need to be created.
	 */
	AST_REDIRECTING_FROM_NAME_VALID,
	AST_REDIRECTING_FROM_NAME_CHAR_SET,
	AST_REDIRECTING_FROM_NAME_PRESENTATION,
	AST_REDIRECTING_FROM_NUMBER_VALID,
	AST_REDIRECTING_FROM_NUMBER_PRESENTATION,
	AST_REDIRECTING_TO_NAME_VALID,
	AST_REDIRECTING_TO_NAME_CHAR_SET,
	AST_REDIRECTING_TO_NAME_PRESENTATION,
	AST_REDIRECTING_TO_NUMBER_VALID,
	AST_REDIRECTING_TO_NUMBER_PRESENTATION,
	AST_REDIRECTING_ORIG_NUMBER,
	AST_REDIRECTING_ORIG_NUMBER_VALID,
	AST_REDIRECTING_ORIG_NUMBER_PLAN,
	AST_REDIRECTING_ORIG_NUMBER_PRESENTATION,
	AST_REDIRECTING_ORIG_NAME,
	AST_REDIRECTING_ORIG_NAME_VALID,
	AST_REDIRECTING_ORIG_NAME_CHAR_SET,
	AST_REDIRECTING_ORIG_NAME_PRESENTATION,
	AST_REDIRECTING_ORIG_SUBADDRESS,
	AST_REDIRECTING_ORIG_SUBADDRESS_TYPE,
	AST_REDIRECTING_ORIG_SUBADDRESS_ODD_EVEN,
	AST_REDIRECTING_ORIG_SUBADDRESS_VALID,
	AST_REDIRECTING_ORIG_TAG,
	AST_REDIRECTING_ORIG_REASON_CODE,
	AST_REDIRECTING_PRIV_TO_NUMBER,
	AST_REDIRECTING_PRIV_TO_NUMBER_PLAN,
	AST_REDIRECTING_PRIV_TO_NUMBER_VALID,
	AST_REDIRECTING_PRIV_TO_NUMBER_PRESENTATION,
	AST_REDIRECTING_PRIV_TO_NAME,
	AST_REDIRECTING_PRIV_TO_NAME_VALID,
	AST_REDIRECTING_PRIV_TO_NAME_CHAR_SET,
	AST_REDIRECTING_PRIV_TO_NAME_PRESENTATION,
	AST_REDIRECTING_PRIV_TO_SUBADDRESS,
	AST_REDIRECTING_PRIV_TO_SUBADDRESS_TYPE,
	AST_REDIRECTING_PRIV_TO_SUBADDRESS_ODD_EVEN,
	AST_REDIRECTING_PRIV_TO_SUBADDRESS_VALID,
	AST_REDIRECTING_PRIV_TO_TAG,
	AST_REDIRECTING_PRIV_FROM_NUMBER,
	AST_REDIRECTING_PRIV_FROM_NUMBER_PLAN,
	AST_REDIRECTING_PRIV_FROM_NUMBER_VALID,
	AST_REDIRECTING_PRIV_FROM_NUMBER_PRESENTATION,
	AST_REDIRECTING_PRIV_FROM_NAME,
	AST_REDIRECTING_PRIV_FROM_NAME_VALID,
	AST_REDIRECTING_PRIV_FROM_NAME_CHAR_SET,
	AST_REDIRECTING_PRIV_FROM_NAME_PRESENTATION,
	AST_REDIRECTING_PRIV_FROM_SUBADDRESS,
	AST_REDIRECTING_PRIV_FROM_SUBADDRESS_TYPE,
	AST_REDIRECTING_PRIV_FROM_SUBADDRESS_ODD_EVEN,
	AST_REDIRECTING_PRIV_FROM_SUBADDRESS_VALID,
	AST_REDIRECTING_PRIV_FROM_TAG,
	AST_REDIRECTING_PRIV_ORIG_NUMBER,
	AST_REDIRECTING_PRIV_ORIG_NUMBER_VALID,
	AST_REDIRECTING_PRIV_ORIG_NUMBER_PLAN,
	AST_REDIRECTING_PRIV_ORIG_NUMBER_PRESENTATION,
	AST_REDIRECTING_PRIV_ORIG_NAME,
	AST_REDIRECTING_PRIV_ORIG_NAME_VALID,
	AST_REDIRECTING_PRIV_ORIG_NAME_CHAR_SET,
	AST_REDIRECTING_PRIV_ORIG_NAME_PRESENTATION,
	AST_REDIRECTING_PRIV_ORIG_SUBADDRESS,
	AST_REDIRECTING_PRIV_ORIG_SUBADDRESS_TYPE,
	AST_REDIRECTING_PRIV_ORIG_SUBADDRESS_ODD_EVEN,
	AST_REDIRECTING_PRIV_ORIG_SUBADDRESS_VALID,
	AST_REDIRECTING_PRIV_ORIG_TAG,
	AST_REDIRECTING_REASON_STR,
	AST_REDIRECTING_ORIG_REASON_STR,
};

struct ast_party_redirecting_reason_ies {
	int code;
	int str;
};

static int redirecting_reason_build_data(unsigned char *data, size_t datalen,
		const struct ast_party_redirecting_reason *reason, const char *label,
		const struct ast_party_redirecting_reason_ies *ies)
{
	size_t length;
	size_t pos = 0;
	int32_t value;

	if (datalen < pos + (sizeof(data[0]) * 2) + sizeof(value)) {
		ast_log(LOG_WARNING, "No space left for %s code\n", label);
		return -1;
	}
	data[pos++] = ies->code;
	data[pos++] = sizeof(value);
	value = htonl(reason->code);
	memcpy(data + pos, &value, sizeof(value));
	pos += sizeof(value);

	if (reason->str) {
		length = strlen(reason->str);
		if (datalen < pos + (sizeof(data[0]) * 2) + length) {
			ast_log(LOG_WARNING, "No space left for %s string\n", label);
			return -1;
		}
		data[pos++] = ies->str;
		data[pos++] = length;
		memcpy(data + pos, reason->str, length);
		pos += length;
	}

	return pos;
}

int ast_redirecting_build_data(unsigned char *data, size_t datalen, const struct ast_party_redirecting *redirecting, const struct ast_set_party_redirecting *update)
{
	int32_t value;
	size_t pos = 0;
	int res;

	static const struct ast_party_id_ies orig_ies = {
		.name.str = AST_REDIRECTING_ORIG_NAME,
		.name.char_set = AST_REDIRECTING_ORIG_NAME_CHAR_SET,
		.name.presentation = AST_REDIRECTING_ORIG_NAME_PRESENTATION,
		.name.valid = AST_REDIRECTING_ORIG_NAME_VALID,

		.number.str = AST_REDIRECTING_ORIG_NUMBER,
		.number.plan = AST_REDIRECTING_ORIG_NUMBER_PLAN,
		.number.presentation = AST_REDIRECTING_ORIG_NUMBER_PRESENTATION,
		.number.valid = AST_REDIRECTING_ORIG_NUMBER_VALID,

		.subaddress.str = AST_REDIRECTING_ORIG_SUBADDRESS,
		.subaddress.type = AST_REDIRECTING_ORIG_SUBADDRESS_TYPE,
		.subaddress.odd_even_indicator = AST_REDIRECTING_ORIG_SUBADDRESS_ODD_EVEN,
		.subaddress.valid = AST_REDIRECTING_ORIG_SUBADDRESS_VALID,

		.tag = AST_REDIRECTING_ORIG_TAG,
		.combined_presentation = 0,/* Not sent. */
	};
	static const struct ast_party_id_ies from_ies = {
		.name.str = AST_REDIRECTING_FROM_NAME,
		.name.char_set = AST_REDIRECTING_FROM_NAME_CHAR_SET,
		.name.presentation = AST_REDIRECTING_FROM_NAME_PRESENTATION,
		.name.valid = AST_REDIRECTING_FROM_NAME_VALID,

		.number.str = AST_REDIRECTING_FROM_NUMBER,
		.number.plan = AST_REDIRECTING_FROM_NUMBER_PLAN,
		.number.presentation = AST_REDIRECTING_FROM_NUMBER_PRESENTATION,
		.number.valid = AST_REDIRECTING_FROM_NUMBER_VALID,

		.subaddress.str = AST_REDIRECTING_FROM_SUBADDRESS,
		.subaddress.type = AST_REDIRECTING_FROM_SUBADDRESS_TYPE,
		.subaddress.odd_even_indicator = AST_REDIRECTING_FROM_SUBADDRESS_ODD_EVEN,
		.subaddress.valid = AST_REDIRECTING_FROM_SUBADDRESS_VALID,

		.tag = AST_REDIRECTING_FROM_TAG,
		.combined_presentation = AST_REDIRECTING_FROM_ID_PRESENTATION,
	};
	static const struct ast_party_id_ies to_ies = {
		.name.str = AST_REDIRECTING_TO_NAME,
		.name.char_set = AST_REDIRECTING_TO_NAME_CHAR_SET,
		.name.presentation = AST_REDIRECTING_TO_NAME_PRESENTATION,
		.name.valid = AST_REDIRECTING_TO_NAME_VALID,

		.number.str = AST_REDIRECTING_TO_NUMBER,
		.number.plan = AST_REDIRECTING_TO_NUMBER_PLAN,
		.number.presentation = AST_REDIRECTING_TO_NUMBER_PRESENTATION,
		.number.valid = AST_REDIRECTING_TO_NUMBER_VALID,

		.subaddress.str = AST_REDIRECTING_TO_SUBADDRESS,
		.subaddress.type = AST_REDIRECTING_TO_SUBADDRESS_TYPE,
		.subaddress.odd_even_indicator = AST_REDIRECTING_TO_SUBADDRESS_ODD_EVEN,
		.subaddress.valid = AST_REDIRECTING_TO_SUBADDRESS_VALID,

		.tag = AST_REDIRECTING_TO_TAG,
		.combined_presentation = AST_REDIRECTING_TO_ID_PRESENTATION,
	};
	static const struct ast_party_id_ies priv_orig_ies = {
		.name.str = AST_REDIRECTING_PRIV_ORIG_NAME,
		.name.char_set = AST_REDIRECTING_PRIV_ORIG_NAME_CHAR_SET,
		.name.presentation = AST_REDIRECTING_PRIV_ORIG_NAME_PRESENTATION,
		.name.valid = AST_REDIRECTING_PRIV_ORIG_NAME_VALID,

		.number.str = AST_REDIRECTING_PRIV_ORIG_NUMBER,
		.number.plan = AST_REDIRECTING_PRIV_ORIG_NUMBER_PLAN,
		.number.presentation = AST_REDIRECTING_PRIV_ORIG_NUMBER_PRESENTATION,
		.number.valid = AST_REDIRECTING_PRIV_ORIG_NUMBER_VALID,

		.subaddress.str = AST_REDIRECTING_PRIV_ORIG_SUBADDRESS,
		.subaddress.type = AST_REDIRECTING_PRIV_ORIG_SUBADDRESS_TYPE,
		.subaddress.odd_even_indicator = AST_REDIRECTING_PRIV_ORIG_SUBADDRESS_ODD_EVEN,
		.subaddress.valid = AST_REDIRECTING_PRIV_ORIG_SUBADDRESS_VALID,

		.tag = AST_REDIRECTING_PRIV_ORIG_TAG,
		.combined_presentation = 0,/* Not sent. */
	};
	static const struct ast_party_id_ies priv_from_ies = {
		.name.str = AST_REDIRECTING_PRIV_FROM_NAME,
		.name.char_set = AST_REDIRECTING_PRIV_FROM_NAME_CHAR_SET,
		.name.presentation = AST_REDIRECTING_PRIV_FROM_NAME_PRESENTATION,
		.name.valid = AST_REDIRECTING_PRIV_FROM_NAME_VALID,

		.number.str = AST_REDIRECTING_PRIV_FROM_NUMBER,
		.number.plan = AST_REDIRECTING_PRIV_FROM_NUMBER_PLAN,
		.number.presentation = AST_REDIRECTING_PRIV_FROM_NUMBER_PRESENTATION,
		.number.valid = AST_REDIRECTING_PRIV_FROM_NUMBER_VALID,

		.subaddress.str = AST_REDIRECTING_PRIV_FROM_SUBADDRESS,
		.subaddress.type = AST_REDIRECTING_PRIV_FROM_SUBADDRESS_TYPE,
		.subaddress.odd_even_indicator = AST_REDIRECTING_PRIV_FROM_SUBADDRESS_ODD_EVEN,
		.subaddress.valid = AST_REDIRECTING_PRIV_FROM_SUBADDRESS_VALID,

		.tag = AST_REDIRECTING_PRIV_FROM_TAG,
		.combined_presentation = 0,/* Not sent. */
	};
	static const struct ast_party_id_ies priv_to_ies = {
		.name.str = AST_REDIRECTING_PRIV_TO_NAME,
		.name.char_set = AST_REDIRECTING_PRIV_TO_NAME_CHAR_SET,
		.name.presentation = AST_REDIRECTING_PRIV_TO_NAME_PRESENTATION,
		.name.valid = AST_REDIRECTING_PRIV_TO_NAME_VALID,

		.number.str = AST_REDIRECTING_PRIV_TO_NUMBER,
		.number.plan = AST_REDIRECTING_PRIV_TO_NUMBER_PLAN,
		.number.presentation = AST_REDIRECTING_PRIV_TO_NUMBER_PRESENTATION,
		.number.valid = AST_REDIRECTING_PRIV_TO_NUMBER_VALID,

		.subaddress.str = AST_REDIRECTING_PRIV_TO_SUBADDRESS,
		.subaddress.type = AST_REDIRECTING_PRIV_TO_SUBADDRESS_TYPE,
		.subaddress.odd_even_indicator = AST_REDIRECTING_PRIV_TO_SUBADDRESS_ODD_EVEN,
		.subaddress.valid = AST_REDIRECTING_PRIV_TO_SUBADDRESS_VALID,

		.tag = AST_REDIRECTING_PRIV_TO_TAG,
		.combined_presentation = 0,/* Not sent. */
	};
	static const struct ast_party_redirecting_reason_ies reason_ies = {
		.code = AST_REDIRECTING_REASON_CODE,
		.str = AST_REDIRECTING_REASON_STR,
	};

	static const struct ast_party_redirecting_reason_ies orig_reason_ies = {
		.code = AST_REDIRECTING_ORIG_REASON_CODE,
		.str = AST_REDIRECTING_ORIG_REASON_STR,
	};

	/* Redirecting frame version */
	if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
		ast_log(LOG_WARNING, "No space left for redirecting frame version\n");
		return -1;
	}
	data[pos++] = AST_REDIRECTING_VERSION;
	data[pos++] = 1;
	data[pos++] = 2;/* Version 1 did not have a version ie */

	res = party_id_build_data(data + pos, datalen - pos, &redirecting->orig,
		"redirecting-orig", &orig_ies, update ? &update->orig : NULL);
	if (res < 0) {
		return -1;
	}
	pos += res;

	res = party_id_build_data(data + pos, datalen - pos, &redirecting->from,
		"redirecting-from", &from_ies, update ? &update->from : NULL);
	if (res < 0) {
		return -1;
	}
	pos += res;

	res = party_id_build_data(data + pos, datalen - pos, &redirecting->to,
		"redirecting-to", &to_ies, update ? &update->to : NULL);
	if (res < 0) {
		return -1;
	}
	pos += res;

	res = party_id_build_data(data + pos, datalen - pos, &redirecting->priv_orig,
		"redirecting-priv-orig", &priv_orig_ies, update ? &update->priv_orig : NULL);
	if (res < 0) {
		return -1;
	}
	pos += res;

	res = party_id_build_data(data + pos, datalen - pos, &redirecting->priv_from,
		"redirecting-priv-from", &priv_from_ies, update ? &update->priv_from : NULL);
	if (res < 0) {
		return -1;
	}
	pos += res;

	res = party_id_build_data(data + pos, datalen - pos, &redirecting->priv_to,
		"redirecting-priv-to", &priv_to_ies, update ? &update->priv_to : NULL);
	if (res < 0) {
		return -1;
	}
	pos += res;

	/* Redirecting reason */
	res = redirecting_reason_build_data(data + pos, datalen - pos, &redirecting->reason,
			"redirecting-reason", &reason_ies);
	if (res < 0) {
		return -1;
	}
	pos += res;

	/* Redirecting original reason */
	res = redirecting_reason_build_data(data + pos, datalen - pos, &redirecting->orig_reason,
			"redirecting-orig-reason", &orig_reason_ies);
	if (res < 0) {
		return -1;
	}
	pos += res;

	/* Redirecting count */
	if (datalen < pos + (sizeof(data[0]) * 2) + sizeof(value)) {
		ast_log(LOG_WARNING, "No space left for redirecting count\n");
		return -1;
	}
	data[pos++] = AST_REDIRECTING_COUNT;
	data[pos++] = sizeof(value);
	value = htonl(redirecting->count);
	memcpy(data + pos, &value, sizeof(value));
	pos += sizeof(value);

	return pos;
}

int ast_redirecting_parse_data(const unsigned char *data, size_t datalen, struct ast_party_redirecting *redirecting)
{
	size_t pos;
	unsigned char ie_len;
	unsigned char ie_id;
	int32_t value;
	int frame_version = 1;
	int from_combined_presentation = 0;
	int got_from_combined_presentation = 0;/* TRUE if got a combined name and number presentation value. */
	int to_combined_presentation = 0;
	int got_to_combined_presentation = 0;/* TRUE if got a combined name and number presentation value. */

	for (pos = 0; pos < datalen; pos += ie_len) {
		if (datalen < pos + sizeof(ie_id) + sizeof(ie_len)) {
			ast_log(LOG_WARNING, "Invalid redirecting update\n");
			return -1;
		}
		ie_id = data[pos++];
		ie_len = data[pos++];
		if (datalen < pos + ie_len) {
			ast_log(LOG_WARNING, "Invalid redirecting update\n");
			return -1;
		}

		switch (ie_id) {
/* Redirecting frame version */
		case AST_REDIRECTING_VERSION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting frame version (%u)\n",
					(unsigned) ie_len);
				break;
			}
			frame_version = data[pos];
			break;
/* Redirecting-orig party id name */
		case AST_REDIRECTING_ORIG_NAME:
			ast_free(redirecting->orig.name.str);
			redirecting->orig.name.str = ast_malloc(ie_len + 1);
			if (redirecting->orig.name.str) {
				memcpy(redirecting->orig.name.str, data + pos, ie_len);
				redirecting->orig.name.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_ORIG_NAME_CHAR_SET:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-orig name char set (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->orig.name.char_set = data[pos];
			break;
		case AST_REDIRECTING_ORIG_NAME_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-orig name presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->orig.name.presentation = data[pos];
			break;
		case AST_REDIRECTING_ORIG_NAME_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-orig name valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->orig.name.valid = data[pos];
			break;
/* Redirecting-orig party id number */
		case AST_REDIRECTING_ORIG_NUMBER:
			ast_free(redirecting->orig.number.str);
			redirecting->orig.number.str = ast_malloc(ie_len + 1);
			if (redirecting->orig.number.str) {
				memcpy(redirecting->orig.number.str, data + pos, ie_len);
				redirecting->orig.number.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_ORIG_NUMBER_PLAN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-orig numbering plan (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->orig.number.plan = data[pos];
			break;
		case AST_REDIRECTING_ORIG_NUMBER_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-orig number presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->orig.number.presentation = data[pos];
			break;
		case AST_REDIRECTING_ORIG_NUMBER_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-orig number valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->orig.number.valid = data[pos];
			break;
/* Redirecting-orig party id subaddress */
		case AST_REDIRECTING_ORIG_SUBADDRESS:
			ast_free(redirecting->orig.subaddress.str);
			redirecting->orig.subaddress.str = ast_malloc(ie_len + 1);
			if (redirecting->orig.subaddress.str) {
				memcpy(redirecting->orig.subaddress.str, data + pos, ie_len);
				redirecting->orig.subaddress.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_ORIG_SUBADDRESS_TYPE:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-orig type of subaddress (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->orig.subaddress.type = data[pos];
			break;
		case AST_REDIRECTING_ORIG_SUBADDRESS_ODD_EVEN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING,
					"Invalid redirecting-orig subaddress odd-even indicator (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->orig.subaddress.odd_even_indicator = data[pos];
			break;
		case AST_REDIRECTING_ORIG_SUBADDRESS_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-orig subaddress valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->orig.subaddress.valid = data[pos];
			break;
/* Redirecting-orig party id tag */
		case AST_REDIRECTING_ORIG_TAG:
			ast_free(redirecting->orig.tag);
			redirecting->orig.tag = ast_malloc(ie_len + 1);
			if (redirecting->orig.tag) {
				memcpy(redirecting->orig.tag, data + pos, ie_len);
				redirecting->orig.tag[ie_len] = 0;
			}
			break;
/* Redirecting-from party id name */
		case AST_REDIRECTING_FROM_NAME:
			ast_free(redirecting->from.name.str);
			redirecting->from.name.str = ast_malloc(ie_len + 1);
			if (redirecting->from.name.str) {
				memcpy(redirecting->from.name.str, data + pos, ie_len);
				redirecting->from.name.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_FROM_NAME_CHAR_SET:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-from name char set (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->from.name.char_set = data[pos];
			break;
		case AST_REDIRECTING_FROM_NAME_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-from name presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->from.name.presentation = data[pos];
			break;
		case AST_REDIRECTING_FROM_NAME_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-from name valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->from.name.valid = data[pos];
			break;
/* Redirecting-from party id number */
		case AST_REDIRECTING_FROM_NUMBER:
			ast_free(redirecting->from.number.str);
			redirecting->from.number.str = ast_malloc(ie_len + 1);
			if (redirecting->from.number.str) {
				memcpy(redirecting->from.number.str, data + pos, ie_len);
				redirecting->from.number.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_FROM_NUMBER_PLAN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-from numbering plan (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->from.number.plan = data[pos];
			break;
		case AST_REDIRECTING_FROM_NUMBER_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-from number presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->from.number.presentation = data[pos];
			break;
		case AST_REDIRECTING_FROM_NUMBER_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-from number valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->from.number.valid = data[pos];
			break;
/* Redirecting-from party id combined presentation */
		case AST_REDIRECTING_FROM_ID_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-from combined presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			from_combined_presentation = data[pos];
			got_from_combined_presentation = 1;
			break;
/* Redirecting-from party id subaddress */
		case AST_REDIRECTING_FROM_SUBADDRESS:
			ast_free(redirecting->from.subaddress.str);
			redirecting->from.subaddress.str = ast_malloc(ie_len + 1);
			if (redirecting->from.subaddress.str) {
				memcpy(redirecting->from.subaddress.str, data + pos, ie_len);
				redirecting->from.subaddress.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_FROM_SUBADDRESS_TYPE:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-from type of subaddress (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->from.subaddress.type = data[pos];
			break;
		case AST_REDIRECTING_FROM_SUBADDRESS_ODD_EVEN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING,
					"Invalid redirecting-from subaddress odd-even indicator (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->from.subaddress.odd_even_indicator = data[pos];
			break;
		case AST_REDIRECTING_FROM_SUBADDRESS_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-from subaddress valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->from.subaddress.valid = data[pos];
			break;
/* Redirecting-from party id tag */
		case AST_REDIRECTING_FROM_TAG:
			ast_free(redirecting->from.tag);
			redirecting->from.tag = ast_malloc(ie_len + 1);
			if (redirecting->from.tag) {
				memcpy(redirecting->from.tag, data + pos, ie_len);
				redirecting->from.tag[ie_len] = 0;
			}
			break;
/* Redirecting-to party id name */
		case AST_REDIRECTING_TO_NAME:
			ast_free(redirecting->to.name.str);
			redirecting->to.name.str = ast_malloc(ie_len + 1);
			if (redirecting->to.name.str) {
				memcpy(redirecting->to.name.str, data + pos, ie_len);
				redirecting->to.name.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_TO_NAME_CHAR_SET:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-to name char set (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->to.name.char_set = data[pos];
			break;
		case AST_REDIRECTING_TO_NAME_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-to name presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->to.name.presentation = data[pos];
			break;
		case AST_REDIRECTING_TO_NAME_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-to name valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->to.name.valid = data[pos];
			break;
/* Redirecting-to party id number */
		case AST_REDIRECTING_TO_NUMBER:
			ast_free(redirecting->to.number.str);
			redirecting->to.number.str = ast_malloc(ie_len + 1);
			if (redirecting->to.number.str) {
				memcpy(redirecting->to.number.str, data + pos, ie_len);
				redirecting->to.number.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_TO_NUMBER_PLAN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-to numbering plan (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->to.number.plan = data[pos];
			break;
		case AST_REDIRECTING_TO_NUMBER_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-to number presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->to.number.presentation = data[pos];
			break;
		case AST_REDIRECTING_TO_NUMBER_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-to number valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->to.number.valid = data[pos];
			break;
/* Redirecting-to party id combined presentation */
		case AST_REDIRECTING_TO_ID_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-to combined presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			to_combined_presentation = data[pos];
			got_to_combined_presentation = 1;
			break;
/* Redirecting-to party id subaddress */
		case AST_REDIRECTING_TO_SUBADDRESS:
			ast_free(redirecting->to.subaddress.str);
			redirecting->to.subaddress.str = ast_malloc(ie_len + 1);
			if (redirecting->to.subaddress.str) {
				memcpy(redirecting->to.subaddress.str, data + pos, ie_len);
				redirecting->to.subaddress.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_TO_SUBADDRESS_TYPE:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-to type of subaddress (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->to.subaddress.type = data[pos];
			break;
		case AST_REDIRECTING_TO_SUBADDRESS_ODD_EVEN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING,
					"Invalid redirecting-to subaddress odd-even indicator (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->to.subaddress.odd_even_indicator = data[pos];
			break;
		case AST_REDIRECTING_TO_SUBADDRESS_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid redirecting-to subaddress valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->to.subaddress.valid = data[pos];
			break;
/* Redirecting-to party id tag */
		case AST_REDIRECTING_TO_TAG:
			ast_free(redirecting->to.tag);
			redirecting->to.tag = ast_malloc(ie_len + 1);
			if (redirecting->to.tag) {
				memcpy(redirecting->to.tag, data + pos, ie_len);
				redirecting->to.tag[ie_len] = 0;
			}
			break;
/* Private redirecting-orig party id name */
		case AST_REDIRECTING_PRIV_ORIG_NAME:
			ast_free(redirecting->priv_orig.name.str);
			redirecting->priv_orig.name.str = ast_malloc(ie_len + 1);
			if (redirecting->priv_orig.name.str) {
				memcpy(redirecting->priv_orig.name.str, data + pos, ie_len);
				redirecting->priv_orig.name.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_PRIV_ORIG_NAME_CHAR_SET:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-orig name char set (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_orig.name.char_set = data[pos];
			break;
		case AST_REDIRECTING_PRIV_ORIG_NAME_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-orig name presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_orig.name.presentation = data[pos];
			break;
		case AST_REDIRECTING_PRIV_ORIG_NAME_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-orig name valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_orig.name.valid = data[pos];
			break;
/* Private redirecting-orig party id number */
		case AST_REDIRECTING_PRIV_ORIG_NUMBER:
			ast_free(redirecting->priv_orig.number.str);
			redirecting->priv_orig.number.str = ast_malloc(ie_len + 1);
			if (redirecting->priv_orig.number.str) {
				memcpy(redirecting->priv_orig.number.str, data + pos, ie_len);
				redirecting->priv_orig.number.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_PRIV_ORIG_NUMBER_PLAN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-orig numbering plan (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_orig.number.plan = data[pos];
			break;
		case AST_REDIRECTING_PRIV_ORIG_NUMBER_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-orig number presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_orig.number.presentation = data[pos];
			break;
		case AST_REDIRECTING_PRIV_ORIG_NUMBER_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-orig number valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_orig.number.valid = data[pos];
			break;
/* Private redirecting-orig party id subaddress */
		case AST_REDIRECTING_PRIV_ORIG_SUBADDRESS:
			ast_free(redirecting->priv_orig.subaddress.str);
			redirecting->priv_orig.subaddress.str = ast_malloc(ie_len + 1);
			if (redirecting->priv_orig.subaddress.str) {
				memcpy(redirecting->priv_orig.subaddress.str, data + pos, ie_len);
				redirecting->priv_orig.subaddress.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_PRIV_ORIG_SUBADDRESS_TYPE:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-orig type of subaddress (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_orig.subaddress.type = data[pos];
			break;
		case AST_REDIRECTING_PRIV_ORIG_SUBADDRESS_ODD_EVEN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING,
					"Invalid private redirecting-orig subaddress odd-even indicator (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_orig.subaddress.odd_even_indicator = data[pos];
			break;
		case AST_REDIRECTING_PRIV_ORIG_SUBADDRESS_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-orig subaddress valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_orig.subaddress.valid = data[pos];
			break;
/* Private redirecting-orig party id tag */
		case AST_REDIRECTING_PRIV_ORIG_TAG:
			ast_free(redirecting->priv_orig.tag);
			redirecting->priv_orig.tag = ast_malloc(ie_len + 1);
			if (redirecting->priv_orig.tag) {
				memcpy(redirecting->priv_orig.tag, data + pos, ie_len);
				redirecting->priv_orig.tag[ie_len] = 0;
			}
			break;
/* Private redirecting-from party id name */
		case AST_REDIRECTING_PRIV_FROM_NAME:
			ast_free(redirecting->priv_from.name.str);
			redirecting->priv_from.name.str = ast_malloc(ie_len + 1);
			if (redirecting->priv_from.name.str) {
				memcpy(redirecting->priv_from.name.str, data + pos, ie_len);
				redirecting->priv_from.name.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_PRIV_FROM_NAME_CHAR_SET:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-from name char set (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_from.name.char_set = data[pos];
			break;
		case AST_REDIRECTING_PRIV_FROM_NAME_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-from name presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_from.name.presentation = data[pos];
			break;
		case AST_REDIRECTING_PRIV_FROM_NAME_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-from name valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_from.name.valid = data[pos];
			break;
/* Private redirecting-from party id number */
		case AST_REDIRECTING_PRIV_FROM_NUMBER:
			ast_free(redirecting->priv_from.number.str);
			redirecting->priv_from.number.str = ast_malloc(ie_len + 1);
			if (redirecting->priv_from.number.str) {
				memcpy(redirecting->priv_from.number.str, data + pos, ie_len);
				redirecting->priv_from.number.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_PRIV_FROM_NUMBER_PLAN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-from numbering plan (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_from.number.plan = data[pos];
			break;
		case AST_REDIRECTING_PRIV_FROM_NUMBER_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-from number presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_from.number.presentation = data[pos];
			break;
		case AST_REDIRECTING_PRIV_FROM_NUMBER_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-from number valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_from.number.valid = data[pos];
			break;
/* Private redirecting-from party id subaddress */
		case AST_REDIRECTING_PRIV_FROM_SUBADDRESS:
			ast_free(redirecting->priv_from.subaddress.str);
			redirecting->priv_from.subaddress.str = ast_malloc(ie_len + 1);
			if (redirecting->priv_from.subaddress.str) {
				memcpy(redirecting->priv_from.subaddress.str, data + pos, ie_len);
				redirecting->priv_from.subaddress.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_PRIV_FROM_SUBADDRESS_TYPE:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-from type of subaddress (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_from.subaddress.type = data[pos];
			break;
		case AST_REDIRECTING_PRIV_FROM_SUBADDRESS_ODD_EVEN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING,
					"Invalid private redirecting-from subaddress odd-even indicator (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_from.subaddress.odd_even_indicator = data[pos];
			break;
		case AST_REDIRECTING_PRIV_FROM_SUBADDRESS_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-from subaddress valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_from.subaddress.valid = data[pos];
			break;
/* Private redirecting-from party id tag */
		case AST_REDIRECTING_PRIV_FROM_TAG:
			ast_free(redirecting->priv_from.tag);
			redirecting->priv_from.tag = ast_malloc(ie_len + 1);
			if (redirecting->priv_from.tag) {
				memcpy(redirecting->priv_from.tag, data + pos, ie_len);
				redirecting->priv_from.tag[ie_len] = 0;
			}
			break;
/* Private redirecting-to party id name */
		case AST_REDIRECTING_PRIV_TO_NAME:
			ast_free(redirecting->priv_to.name.str);
			redirecting->priv_to.name.str = ast_malloc(ie_len + 1);
			if (redirecting->priv_to.name.str) {
				memcpy(redirecting->priv_to.name.str, data + pos, ie_len);
				redirecting->priv_to.name.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_PRIV_TO_NAME_CHAR_SET:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-to name char set (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_to.name.char_set = data[pos];
			break;
		case AST_REDIRECTING_PRIV_TO_NAME_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-to name presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_to.name.presentation = data[pos];
			break;
		case AST_REDIRECTING_PRIV_TO_NAME_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-to name valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_to.name.valid = data[pos];
			break;
/* Private redirecting-to party id number */
		case AST_REDIRECTING_PRIV_TO_NUMBER:
			ast_free(redirecting->priv_to.number.str);
			redirecting->priv_to.number.str = ast_malloc(ie_len + 1);
			if (redirecting->priv_to.number.str) {
				memcpy(redirecting->priv_to.number.str, data + pos, ie_len);
				redirecting->priv_to.number.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_PRIV_TO_NUMBER_PLAN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-to numbering plan (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_to.number.plan = data[pos];
			break;
		case AST_REDIRECTING_PRIV_TO_NUMBER_PRESENTATION:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-to number presentation (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_to.number.presentation = data[pos];
			break;
		case AST_REDIRECTING_PRIV_TO_NUMBER_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-to number valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_to.number.valid = data[pos];
			break;
/* Private redirecting-to party id subaddress */
		case AST_REDIRECTING_PRIV_TO_SUBADDRESS:
			ast_free(redirecting->priv_to.subaddress.str);
			redirecting->priv_to.subaddress.str = ast_malloc(ie_len + 1);
			if (redirecting->priv_to.subaddress.str) {
				memcpy(redirecting->priv_to.subaddress.str, data + pos, ie_len);
				redirecting->priv_to.subaddress.str[ie_len] = 0;
			}
			break;
		case AST_REDIRECTING_PRIV_TO_SUBADDRESS_TYPE:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-to type of subaddress (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_to.subaddress.type = data[pos];
			break;
		case AST_REDIRECTING_PRIV_TO_SUBADDRESS_ODD_EVEN:
			if (ie_len != 1) {
				ast_log(LOG_WARNING,
					"Invalid private redirecting-to subaddress odd-even indicator (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_to.subaddress.odd_even_indicator = data[pos];
			break;
		case AST_REDIRECTING_PRIV_TO_SUBADDRESS_VALID:
			if (ie_len != 1) {
				ast_log(LOG_WARNING, "Invalid private redirecting-to subaddress valid (%u)\n",
					(unsigned) ie_len);
				break;
			}
			redirecting->priv_to.subaddress.valid = data[pos];
			break;
/* Private redirecting-to party id tag */
		case AST_REDIRECTING_PRIV_TO_TAG:
			ast_free(redirecting->priv_to.tag);
			redirecting->priv_to.tag = ast_malloc(ie_len + 1);
			if (redirecting->priv_to.tag) {
				memcpy(redirecting->priv_to.tag, data + pos, ie_len);
				redirecting->priv_to.tag[ie_len] = 0;
			}
			break;
/* Redirecting reason code */
		case AST_REDIRECTING_REASON_CODE:
			if (ie_len != sizeof(value)) {
				ast_log(LOG_WARNING, "Invalid redirecting reason (%u)\n",
					(unsigned) ie_len);
				break;
			}
			memcpy(&value, data + pos, sizeof(value));
			redirecting->reason.code = ntohl(value);
			break;
/* Redirecting reason string */
		case AST_REDIRECTING_REASON_STR:
			ast_free(redirecting->reason.str);
			redirecting->reason.str = ast_malloc(ie_len + 1);
			if (redirecting->reason.str) {
				memcpy(redirecting->reason.str, data + pos, ie_len);
				redirecting->reason.str[ie_len] = 0;
			}
			break;
/* Redirecting orig-reason code */
		case AST_REDIRECTING_ORIG_REASON_CODE:
			if (ie_len != sizeof(value)) {
				ast_log(LOG_WARNING, "Invalid redirecting original reason (%u)\n",
					(unsigned) ie_len);
				break;
			}
			memcpy(&value, data + pos, sizeof(value));
			redirecting->orig_reason.code = ntohl(value);
			break;
/* Redirecting orig-reason string */
		case AST_REDIRECTING_ORIG_REASON_STR:
			ast_free(redirecting->orig_reason.str);
			redirecting->orig_reason.str = ast_malloc(ie_len + 1);
			if (redirecting->orig_reason.str) {
				memcpy(redirecting->orig_reason.str, data + pos, ie_len);
				redirecting->orig_reason.str[ie_len] = 0;
			}
			break;
/* Redirecting count */
		case AST_REDIRECTING_COUNT:
			if (ie_len != sizeof(value)) {
				ast_log(LOG_WARNING, "Invalid redirecting count (%u)\n",
					(unsigned) ie_len);
				break;
			}
			memcpy(&value, data + pos, sizeof(value));
			redirecting->count = ntohl(value);
			break;
/* Redirecting unknown element */
		default:
			ast_debug(1, "Unknown redirecting element: %u (%u)\n",
				(unsigned) ie_id, (unsigned) ie_len);
			break;
		}
	}

	switch (frame_version) {
	case 1:
		/*
		 * The other end is an earlier version that we need to adjust
		 * for compatibility.
		 *
		 * The earlier version did not have the orig party id or
		 * orig_reason value.
		 */
		redirecting->from.name.valid = 1;
		redirecting->from.name.char_set = AST_PARTY_CHAR_SET_ISO8859_1;
		redirecting->from.number.valid = 1;
		if (got_from_combined_presentation) {
			redirecting->from.name.presentation = from_combined_presentation;
			redirecting->from.number.presentation = from_combined_presentation;
		}

		redirecting->to.name.valid = 1;
		redirecting->to.name.char_set = AST_PARTY_CHAR_SET_ISO8859_1;
		redirecting->to.number.valid = 1;
		if (got_to_combined_presentation) {
			redirecting->to.name.presentation = to_combined_presentation;
			redirecting->to.number.presentation = to_combined_presentation;
		}
		break;
	case 2:
		/* The other end is at the same level as we are. */
		break;
	default:
		/*
		 * The other end is newer than we are.
		 * We need to assume that they are compatible with us.
		 */
		ast_debug(1, "Redirecting frame has newer version: %u\n",
			(unsigned) frame_version);
		break;
	}

	return 0;
}

void ast_channel_update_redirecting(struct ast_channel *chan, const struct ast_party_redirecting *redirecting, const struct ast_set_party_redirecting *update)
{
	unsigned char data[1024];	/* This should be large enough */
	size_t datalen;

	datalen = ast_redirecting_build_data(data, sizeof(data), redirecting, update);
	if (datalen == (size_t) -1) {
		return;
	}

	ast_indicate_data(chan, AST_CONTROL_REDIRECTING, data, datalen);
}

void ast_channel_queue_redirecting_update(struct ast_channel *chan, const struct ast_party_redirecting *redirecting, const struct ast_set_party_redirecting *update)
{
	unsigned char data[1024];	/* This should be large enough */
	size_t datalen;

	datalen = ast_redirecting_build_data(data, sizeof(data), redirecting, update);
	if (datalen == (size_t) -1) {
		return;
	}

	ast_queue_control_data(chan, AST_CONTROL_REDIRECTING, data, datalen);
}

/*!
 * Storage to determine if the current thread is running an intercept dialplan routine.
 */
AST_THREADSTORAGE_RAW(in_intercept_routine);

/*!
 * \internal
 * \brief Set the current intercept dialplan routine status mode.
 * \since 13.14.0
 *
 * \param in_intercept_mode New intercept mode.  (Non-zero if in intercept mode)
 *
 * \return Nothing
 */
static void channel_set_intercept_mode(int in_intercept_mode)
{
	int status;

	status = ast_threadstorage_set_ptr(&in_intercept_routine,
		in_intercept_mode ? (void *) 1 : (void *) 0);
	if (status) {
		ast_log(LOG_ERROR, "Failed to set dialplan intercept mode\n");
	}
}

int ast_channel_get_intercept_mode(void)
{
	return ast_threadstorage_get_ptr(&in_intercept_routine) ? 1 : 0;
}

int ast_channel_connected_line_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const void *connected_info, int is_caller, int is_frame)
{
	static int deprecation_warning = 0;
	const char *macro;
	const char *macro_args;
	int retval;

	ast_channel_lock(macro_chan);
	macro = pbx_builtin_getvar_helper(macro_chan, is_caller
		? "CONNECTED_LINE_CALLER_SEND_MACRO" : "CONNECTED_LINE_CALLEE_SEND_MACRO");
	macro = ast_strdupa(S_OR(macro, ""));
	macro_args = pbx_builtin_getvar_helper(macro_chan, is_caller
		? "CONNECTED_LINE_CALLER_SEND_MACRO_ARGS" : "CONNECTED_LINE_CALLEE_SEND_MACRO_ARGS");
	macro_args = ast_strdupa(S_OR(macro_args, ""));

	if (ast_strlen_zero(macro)) {
		ast_channel_unlock(macro_chan);
		return -1;
	}

	if (!deprecation_warning) {
		deprecation_warning = 1;
		ast_log(LOG_WARNING, "Usage of CONNECTED_LINE_CALLE[ER]_SEND_MACRO is deprecated.  Please use CONNECTED_LINE_SEND_SUB instead.\n");
	}
	if (is_frame) {
		const struct ast_frame *frame = connected_info;

		ast_connected_line_parse_data(frame->data.ptr, frame->datalen, ast_channel_connected(macro_chan));
	} else {
		const struct ast_party_connected_line *connected = connected_info;

		ast_party_connected_line_copy(ast_channel_connected(macro_chan), connected);
	}
	ast_channel_unlock(macro_chan);

	channel_set_intercept_mode(1);
	retval = ast_app_run_macro(autoservice_chan, macro_chan, macro, macro_args);
	channel_set_intercept_mode(0);
	if (!retval) {
		struct ast_party_connected_line saved_connected;

		ast_party_connected_line_init(&saved_connected);
		ast_channel_lock(macro_chan);
		ast_party_connected_line_copy(&saved_connected, ast_channel_connected(macro_chan));
		ast_channel_unlock(macro_chan);
		ast_channel_update_connected_line(macro_chan, &saved_connected, NULL);
		ast_party_connected_line_free(&saved_connected);
	}

	return retval;
}

int ast_channel_redirecting_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const void *redirecting_info, int is_caller, int is_frame)
{
	static int deprecation_warning = 0;
	const char *macro;
	const char *macro_args;
	int retval;

	ast_channel_lock(macro_chan);
	macro = pbx_builtin_getvar_helper(macro_chan, is_caller
		? "REDIRECTING_CALLER_SEND_MACRO" : "REDIRECTING_CALLEE_SEND_MACRO");
	macro = ast_strdupa(S_OR(macro, ""));
	macro_args = pbx_builtin_getvar_helper(macro_chan, is_caller
		? "REDIRECTING_CALLER_SEND_MACRO_ARGS" : "REDIRECTING_CALLEE_SEND_MACRO_ARGS");
	macro_args = ast_strdupa(S_OR(macro_args, ""));

	if (ast_strlen_zero(macro)) {
		ast_channel_unlock(macro_chan);
		return -1;
	}

	if (!deprecation_warning) {
		deprecation_warning = 1;
		ast_log(LOG_WARNING, "Usage of REDIRECTING_CALLE[ER]_SEND_MACRO is deprecated.  Please use REDIRECTING_SEND_SUB instead.\n");
	}
	if (is_frame) {
		const struct ast_frame *frame = redirecting_info;

		ast_redirecting_parse_data(frame->data.ptr, frame->datalen, ast_channel_redirecting(macro_chan));
	} else {
		const struct ast_party_redirecting *redirecting = redirecting_info;

		ast_party_redirecting_copy(ast_channel_redirecting(macro_chan), redirecting);
	}
	ast_channel_unlock(macro_chan);

	channel_set_intercept_mode(1);
	retval = ast_app_run_macro(autoservice_chan, macro_chan, macro, macro_args);
	channel_set_intercept_mode(0);
	if (!retval) {
		struct ast_party_redirecting saved_redirecting;

		ast_party_redirecting_init(&saved_redirecting);
		ast_channel_lock(macro_chan);
		ast_party_redirecting_copy(&saved_redirecting, ast_channel_redirecting(macro_chan));
		ast_channel_unlock(macro_chan);
		ast_channel_update_redirecting(macro_chan, &saved_redirecting, NULL);
		ast_party_redirecting_free(&saved_redirecting);
	}

	return retval;
}

int ast_channel_connected_line_sub(struct ast_channel *autoservice_chan, struct ast_channel *sub_chan, const void *connected_info, int is_frame)
{
	const char *sub;
	const char *sub_args;
	int retval;

	ast_channel_lock(sub_chan);
	sub = pbx_builtin_getvar_helper(sub_chan, "CONNECTED_LINE_SEND_SUB");
	sub = ast_strdupa(S_OR(sub, ""));
	sub_args = pbx_builtin_getvar_helper(sub_chan, "CONNECTED_LINE_SEND_SUB_ARGS");
	sub_args = ast_strdupa(S_OR(sub_args, ""));

	if (ast_strlen_zero(sub)) {
		ast_channel_unlock(sub_chan);
		return -1;
	}

	if (is_frame) {
		const struct ast_frame *frame = connected_info;

		ast_connected_line_parse_data(frame->data.ptr, frame->datalen, ast_channel_connected(sub_chan));
	} else {
		const struct ast_party_connected_line *connected = connected_info;

		ast_party_connected_line_copy(ast_channel_connected(sub_chan), connected);
	}
	ast_channel_unlock(sub_chan);

	channel_set_intercept_mode(1);
	retval = ast_app_run_sub(autoservice_chan, sub_chan, sub, sub_args, 0);
	channel_set_intercept_mode(0);
	if (!retval) {
		struct ast_party_connected_line saved_connected;

		ast_party_connected_line_init(&saved_connected);
		ast_channel_lock(sub_chan);
		ast_party_connected_line_copy(&saved_connected, ast_channel_connected(sub_chan));
		ast_channel_unlock(sub_chan);
		ast_channel_update_connected_line(sub_chan, &saved_connected, NULL);
		ast_party_connected_line_free(&saved_connected);
	}

	return retval;
}

int ast_channel_redirecting_sub(struct ast_channel *autoservice_chan, struct ast_channel *sub_chan, const void *redirecting_info, int is_frame)
{
	const char *sub;
	const char *sub_args;
	int retval;

	ast_channel_lock(sub_chan);
	sub = pbx_builtin_getvar_helper(sub_chan, "REDIRECTING_SEND_SUB");
	sub = ast_strdupa(S_OR(sub, ""));
	sub_args = pbx_builtin_getvar_helper(sub_chan, "REDIRECTING_SEND_SUB_ARGS");
	sub_args = ast_strdupa(S_OR(sub_args, ""));

	if (ast_strlen_zero(sub)) {
		ast_channel_unlock(sub_chan);
		return -1;
	}

	if (is_frame) {
		const struct ast_frame *frame = redirecting_info;

		ast_redirecting_parse_data(frame->data.ptr, frame->datalen, ast_channel_redirecting(sub_chan));
	} else {
		const struct ast_party_redirecting *redirecting = redirecting_info;

		ast_party_redirecting_copy(ast_channel_redirecting(sub_chan), redirecting);
	}
	ast_channel_unlock(sub_chan);

	channel_set_intercept_mode(1);
	retval = ast_app_run_sub(autoservice_chan, sub_chan, sub, sub_args, 0);
	channel_set_intercept_mode(0);
	if (!retval) {
		struct ast_party_redirecting saved_redirecting;

		ast_party_redirecting_init(&saved_redirecting);
		ast_channel_lock(sub_chan);
		ast_party_redirecting_copy(&saved_redirecting, ast_channel_redirecting(sub_chan));
		ast_channel_unlock(sub_chan);
		ast_channel_update_redirecting(sub_chan, &saved_redirecting, NULL);
		ast_party_redirecting_free(&saved_redirecting);
	}

	return retval;
}

static void *channel_cc_params_copy(void *data)
{
	const struct ast_cc_config_params *src = data;
	struct ast_cc_config_params *dest = ast_cc_config_params_init();
	if (!dest) {
		return NULL;
	}
	ast_cc_copy_config_params(dest, src);
	return dest;
}

static void channel_cc_params_destroy(void *data)
{
	struct ast_cc_config_params *cc_params = data;
	ast_cc_config_params_destroy(cc_params);
}

static const struct ast_datastore_info cc_channel_datastore_info = {
	.type = "Call Completion",
	.duplicate = channel_cc_params_copy,
	.destroy = channel_cc_params_destroy,
};

int ast_channel_cc_params_init(struct ast_channel *chan,
		const struct ast_cc_config_params *base_params)
{
	struct ast_cc_config_params *cc_params;
	struct ast_datastore *cc_datastore;

	if (!(cc_params = ast_cc_config_params_init())) {
		return -1;
	}

	if (!(cc_datastore = ast_datastore_alloc(&cc_channel_datastore_info, NULL))) {
		ast_cc_config_params_destroy(cc_params);
		return -1;
	}

	if (base_params) {
		ast_cc_copy_config_params(cc_params, base_params);
	}
	cc_datastore->data = cc_params;
	ast_channel_datastore_add(chan, cc_datastore);
	return 0;
}

struct ast_cc_config_params *ast_channel_get_cc_config_params(struct ast_channel *chan)
{
	struct ast_datastore *cc_datastore;

	if (!(cc_datastore = ast_channel_datastore_find(chan, &cc_channel_datastore_info, NULL))) {
		/* If we can't find the datastore, it almost definitely means that the channel type being
		 * used has not had its driver modified to parse CC config parameters. The best action
		 * to take here is to create the parameters on the spot with the defaults set.
		 */
		if (ast_channel_cc_params_init(chan, NULL)) {
			return NULL;
		}
		if (!(cc_datastore = ast_channel_datastore_find(chan, &cc_channel_datastore_info, NULL))) {
			/* Should be impossible */
			return NULL;
		}
	}

	ast_assert(cc_datastore->data != NULL);
	return cc_datastore->data;
}

int ast_channel_get_device_name(struct ast_channel *chan, char *device_name, size_t name_buffer_length)
{
	int len = name_buffer_length;
	char *dash;
	if (!ast_channel_queryoption(chan, AST_OPTION_DEVICE_NAME, device_name, &len, 0)) {
		return 0;
	}

	/* Dang. Do it the old-fashioned way */
	ast_copy_string(device_name, ast_channel_name(chan), name_buffer_length);
	if ((dash = strrchr(device_name, '-'))) {
		*dash = '\0';
	}

	return 0;
}

int ast_channel_get_cc_agent_type(struct ast_channel *chan, char *agent_type, size_t size)
{
	int len = size;
	char *slash;

	if (!ast_channel_queryoption(chan, AST_OPTION_CC_AGENT_TYPE, agent_type, &len, 0)) {
		return 0;
	}

	ast_copy_string(agent_type, ast_channel_name(chan), size);
	if ((slash = strchr(agent_type, '/'))) {
		*slash = '\0';
	}
	return 0;
}

void ast_channel_unlink(struct ast_channel *chan)
{
	ao2_unlink(channels, chan);
}

struct ast_bridge *ast_channel_get_bridge(const struct ast_channel *chan)
{
	struct ast_bridge *bridge;

	bridge = ast_channel_internal_bridge(chan);
	if (bridge) {
		ao2_ref(bridge, +1);
	}
	return bridge;
}

int ast_channel_is_bridged(const struct ast_channel *chan)
{
	return ast_channel_internal_bridge(chan) != NULL;
}

int ast_channel_is_leaving_bridge(struct ast_channel *chan)
{
	int hangup_flags = ast_channel_softhangup_internal_flag(chan);
	int hangup_test = hangup_flags & AST_SOFTHANGUP_ASYNCGOTO;
	int unbridge = ast_channel_unbridged(chan);

	/* This function should only return true if either the unbridged flag or
	 * the ASYNCGOTO soft hangup flag is set and when no other soft hangup
	 * flags are set. Any other soft hangup flags being set should make it
	 * return false.
	 */
	return ((hangup_test || unbridge) && (hangup_test == hangup_flags));
}

struct ast_channel *ast_channel_bridge_peer(struct ast_channel *chan)
{
	struct ast_channel *peer;
	struct ast_bridge *bridge;

	/* Get the bridge the channel is in. */
	ast_channel_lock(chan);
	bridge = ast_channel_get_bridge(chan);
	ast_channel_unlock(chan);
	if (!bridge) {
		return NULL;
	}

	peer = ast_bridge_peer(bridge, chan);
	ao2_ref(bridge, -1);
	return peer;
}

struct ast_bridge_channel *ast_channel_get_bridge_channel(struct ast_channel *chan)
{
	struct ast_bridge_channel *bridge_channel;

	bridge_channel = ast_channel_internal_bridge_channel(chan);
	if (bridge_channel) {
		ao2_ref(bridge_channel, +1);
	}
	return bridge_channel;
}

struct ast_channel *ast_channel_yank(struct ast_channel *yankee)
{
	struct ast_channel *yanked_chan;
	struct {
		char *accountcode;
		char *exten;
		char *context;
		char *name;
		int amaflags;
		int priority;
		struct ast_format *readformat;
		struct ast_format *writeformat;
	} my_vars = { 0, };

	ast_channel_lock(yankee);
	my_vars.accountcode = ast_strdupa(ast_channel_accountcode(yankee));
	my_vars.exten = ast_strdupa(ast_channel_exten(yankee));
	my_vars.context = ast_strdupa(ast_channel_context(yankee));
	my_vars.name = ast_strdupa(ast_channel_name(yankee));
	my_vars.amaflags = ast_channel_amaflags(yankee);
	my_vars.priority = ast_channel_priority(yankee);
	/* The priority as returned by ast_channel_yank is where the channel
	 * should go if the dialplan is executed on it. If the channel is
	 * already executing dialplan then the priority currently set is
	 * where it is currently. We increment it so it becomes where it should
	 * execute.
	 */
	if (ast_test_flag(ast_channel_flags(yankee), AST_FLAG_IN_AUTOLOOP)) {
		my_vars.priority++;
	}
	my_vars.writeformat = ao2_bump(ast_channel_writeformat(yankee));
	my_vars.readformat = ao2_bump(ast_channel_readformat(yankee));
	ast_channel_unlock(yankee);

	/* Do not hold any channel locks while calling channel_alloc() since the function
	 * locks the channel container when linking the new channel in. */
	if (!(yanked_chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, my_vars.accountcode,
					my_vars.exten, my_vars.context, NULL, yankee, my_vars.amaflags,
					"Surrogate/%s", my_vars.name))) {
		ao2_cleanup(my_vars.writeformat);
		ao2_cleanup(my_vars.readformat);
		return NULL;
	}

	/* Make formats okay */
	ast_channel_set_readformat(yanked_chan, my_vars.readformat);
	ast_channel_set_writeformat(yanked_chan, my_vars.writeformat);
	ao2_cleanup(my_vars.readformat);
	ao2_cleanup(my_vars.writeformat);
	ast_channel_priority_set(yanked_chan, my_vars.priority);

	ast_channel_unlock(yanked_chan);

	if (ast_channel_move(yanked_chan, yankee)) {
		ast_hangup(yanked_chan);
		return NULL;
	}

	return yanked_chan;
}

/*!
 * Mutex that prevents multiple ast_channel_move() operations
 * from occurring simultaneously. This is necessary since the
 * involved channels have to be locked and unlocked throughout
 * the move operation.
 *
 * The most important data being protected are the masq and masqr
 * data on channels. We don't want them getting criss-crossed due
 * to multiple moves mucking with them.
 */
AST_MUTEX_DEFINE_STATIC(channel_move_lock);

int ast_channel_move(struct ast_channel *dest, struct ast_channel *source)
{
	SCOPED_MUTEX(lock, &channel_move_lock);

	if (dest == source) {
		ast_log(LOG_WARNING, "Can't move channel '%s' into itself!\n",
			ast_channel_name(dest));
		return -1;
	}

	ast_channel_lock_both(dest, source);

	if (ast_test_flag(ast_channel_flags(dest), AST_FLAG_ZOMBIE)
		|| ast_test_flag(ast_channel_flags(source), AST_FLAG_ZOMBIE)) {
		/* Zombies! Run! */
		ast_log(LOG_WARNING,
			"Can't move channel. One or both is dead (%s <-- %s)\n",
			ast_channel_name(dest), ast_channel_name(source));
		ast_channel_unlock(source);
		ast_channel_unlock(dest);
		return -1;
	}

	ast_channel_masq_set(dest, source);
	ast_channel_masqr_set(source, dest);

	ast_channel_unlock(dest);
	ast_channel_unlock(source);

	channel_do_masquerade(dest, source);
	return 0;
}

static void suppress_datastore_destroy_cb(void *data)
{
	ao2_cleanup(data);
}

static const struct ast_datastore_info suppress_datastore_voice = {
	.type = "suppressvoice",
	.destroy = suppress_datastore_destroy_cb
};

static void suppress_framehook_destroy_cb(void *data)
{
	ao2_cleanup(data);
}

struct suppress_data {
	enum ast_frame_type frametype;
	unsigned int direction;
	int framehook_id;
};

static void suppress_framehook_fixup_cb(void *data, int framehook_id, struct ast_channel *old_chan, struct ast_channel *new_chan)
{
	struct suppress_data *suppress = data;

	suppress->framehook_id = framehook_id;
}

static struct ast_frame *suppress_framehook_event_cb(struct ast_channel *chan, struct ast_frame *frame, enum ast_framehook_event event, void *data)
{
	struct suppress_data *suppress = data;
	int suppress_frame = 0;

	if (!frame) {
		return NULL;
	}

	if (frame->frametype != suppress->frametype) {
		return frame;
	}

	if (event == AST_FRAMEHOOK_EVENT_READ && (suppress->direction & AST_MUTE_DIRECTION_READ)) {
		suppress_frame = 1;
	} else if (event == AST_FRAMEHOOK_EVENT_WRITE && (suppress->direction & AST_MUTE_DIRECTION_WRITE)) {
		suppress_frame = 1;
	}

	if (suppress_frame) {
		switch (frame->frametype) {
		case AST_FRAME_VOICE:
			frame = &ast_null_frame;
			break;
		default:
			break;
		}
	}

	return frame;
}

static const struct ast_datastore_info *suppress_get_datastore_information(enum ast_frame_type frametype)
{
	switch (frametype) {
	case AST_FRAME_VOICE:
		return &suppress_datastore_voice;
	default:
		return NULL;
	}
}

int ast_channel_suppress(struct ast_channel *chan, unsigned int direction, enum ast_frame_type frametype)
{
	struct suppress_data *suppress;
	const struct ast_datastore_info *datastore_info = NULL;
	struct ast_datastore *datastore = NULL;
	struct ast_framehook_interface interface = {
		.version = AST_FRAMEHOOK_INTERFACE_VERSION,
		.event_cb = suppress_framehook_event_cb,
		.destroy_cb = suppress_framehook_destroy_cb,
		.chan_fixup_cb = suppress_framehook_fixup_cb,
	};
	int framehook_id;

	if (!(datastore_info = suppress_get_datastore_information(frametype))) {
		ast_log(LOG_WARNING, "Attempted to suppress an unsupported frame type (%u).\n", frametype);
		return -1;
	}

	if ((datastore = ast_channel_datastore_find(chan, datastore_info, NULL))) {
		suppress = datastore->data;
		suppress->direction |= direction;
		return 0;
	}

	if (!(suppress = ao2_alloc(sizeof(*suppress), NULL))) {
		ast_log(LOG_WARNING, "Failed to allocate data while attempting to suppress a stream.\n");
		return -1;
	}

	suppress->frametype = frametype;
	suppress->direction |= direction;

	interface.data = suppress;

	framehook_id = ast_framehook_attach(chan, &interface);
	if (framehook_id < 0) {
		/* Hook attach failed.  Get rid of the evidence. */
		ast_log(LOG_WARNING, "Failed to attach framehook while attempting to suppress a stream.\n");
		ao2_ref(suppress, -1);
		return -1;
	}

	/* One ref for the framehook */
	ao2_ref(suppress, +1);

	suppress->framehook_id = framehook_id;

	if (!(datastore = ast_datastore_alloc(datastore_info, NULL))) {
		ast_log(LOG_WARNING, "Failed to allocate datastore while attempting to suppress a stream.\n");
		ast_framehook_detach(chan, framehook_id);
		ao2_ref(suppress, -1);
		return -1;
	}

	/* the ref provided by the allocation is taken by the datastore */
	datastore->data = suppress;

	ast_channel_datastore_add(chan, datastore);

	return 0;
}

int ast_channel_unsuppress(struct ast_channel *chan, unsigned int direction, enum ast_frame_type frametype)
{
	const struct ast_datastore_info *datastore_info = NULL;
	struct ast_datastore *datastore = NULL;
	struct suppress_data *suppress;

	if (!(datastore_info = suppress_get_datastore_information(frametype))) {
		ast_log(LOG_WARNING, "Attempted to unsuppress an unsupported frame type (%u).\n", frametype);
		return -1;
	}

	if (!(datastore = ast_channel_datastore_find(chan, datastore_info, NULL))) {
		/* Nothing to do! */
		return 0;
	}

	suppress = datastore->data;

	suppress->direction &= ~(direction);

	if (suppress->direction == 0) {
		/* Nothing left to suppress.  Bye! */
		ast_framehook_detach(chan, suppress->framehook_id);
		ast_channel_datastore_remove(chan, datastore);
		ast_datastore_free(datastore);
	}

	return 0;
}

void ast_channel_end_dtmf(struct ast_channel *chan, char digit, struct timeval start, const char *why)
{
	int dead;
	long duration;

	ast_channel_lock(chan);
	dead = ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)
		|| (ast_channel_softhangup_internal_flag(chan)
			& ~AST_SOFTHANGUP_ASYNCGOTO);
	ast_channel_unlock(chan);
	if (dead) {
		/* Channel is a zombie or a real hangup. */
		return;
	}

	duration = ast_tvdiff_ms(ast_tvnow(), start);
	if (duration < option_dtmfminduration) {
		duration = option_dtmfminduration;
	}
	ast_senddigit_end(chan, digit, duration);
	ast_log(LOG_DTMF, "DTMF end '%c' simulated on %s due to %s, duration %ld ms\n",
		digit, ast_channel_name(chan), why, duration);
}

static void features_destroy(void *obj)
{
	ast_bridge_features_destroy(obj);
}

static const struct ast_datastore_info bridge_features_info = {
	.type = "bridge-features",
	.destroy = features_destroy,
};

struct ast_bridge_features *ast_channel_feature_hooks_get(struct ast_channel *chan)
{
	struct ast_datastore *datastore;

	datastore = ast_channel_datastore_find(chan, &bridge_features_info, NULL);
	if (!datastore) {
		return NULL;
	}
	return datastore->data;
}

static int channel_feature_hooks_set_full(struct ast_channel *chan, struct ast_bridge_features *features, int replace)
{
	struct ast_datastore *datastore;
	struct ast_bridge_features *ds_features;

	datastore = ast_channel_datastore_find(chan, &bridge_features_info, NULL);
	if (datastore) {
		ds_features = datastore->data;
		if (replace) {
			ast_bridge_features_cleanup(ds_features);
			ast_bridge_features_init(ds_features);
		}
		if (features) {
			ast_bridge_features_merge(ds_features, features);
		}
		return 0;
	}

	datastore = ast_datastore_alloc(&bridge_features_info, NULL);
	if (!datastore) {
		return -1;
	}

	ds_features = ast_bridge_features_new();
	if (!ds_features) {
		ast_datastore_free(datastore);
		return -1;
	}

	if (features) {
		ast_bridge_features_merge(ds_features, features);
	}
	datastore->data = ds_features;
	ast_channel_datastore_add(chan, datastore);
	return 0;
}

int ast_channel_feature_hooks_append(struct ast_channel *chan, struct ast_bridge_features *features)
{
	return channel_feature_hooks_set_full(chan, features, 0);
}

int ast_channel_feature_hooks_replace(struct ast_channel *chan, struct ast_bridge_features *features)
{
	return channel_feature_hooks_set_full(chan, features, 1);
}

enum ast_channel_error ast_channel_errno(void)
{
	return ast_channel_internal_errno();
}

int ast_channel_request_stream_topology_change(struct ast_channel *chan,
		struct ast_stream_topology *topology, void *change_source)
{
	int res;

	ast_assert(chan != NULL);
	ast_assert(topology != NULL);

	ast_channel_lock(chan);
	if (!ast_channel_is_multistream(chan) || !ast_channel_tech(chan)->indicate) {
		ast_channel_unlock(chan);
		return -1;
	}

	if (ast_stream_topology_equal(ast_channel_get_stream_topology(chan), topology)) {
		ast_debug(3, "Topology of %s already matches what is requested so ignoring topology change request\n",
				ast_channel_name(chan));
		ast_channel_unlock(chan);
		return 0;
	}

	ast_channel_internal_set_stream_topology_change_source(chan, change_source);

	res = ast_channel_tech(chan)->indicate(chan, AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE, topology, sizeof(topology));
	ast_channel_unlock(chan);
	return res;
}

int ast_channel_stream_topology_changed(struct ast_channel *chan, struct ast_stream_topology *topology)
{
	ast_assert(chan != NULL);
	ast_assert(topology != NULL);

	if (!ast_channel_is_multistream(chan) || !ast_channel_tech(chan)->indicate) {
		return -1;
	}

	return ast_channel_tech(chan)->indicate(chan, AST_CONTROL_STREAM_TOPOLOGY_CHANGED, topology, sizeof(topology));
}

void ast_channel_set_flag(struct ast_channel *chan, unsigned int flag)
{
	ast_channel_lock(chan);
	ast_set_flag(ast_channel_flags(chan), flag);
	ast_channel_unlock(chan);
}

void ast_channel_clear_flag(struct ast_channel *chan, unsigned int flag)
{
	ast_channel_lock(chan);
	ast_clear_flag(ast_channel_flags(chan), flag);
	ast_channel_unlock(chan);
}