aboutsummaryrefslogtreecommitdiff
path: root/src/java/com/android/ims/ImsManager.java
blob: b5a1168b8c2f56247fe32c80b8fbeb7c0fd8a150 (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
/*
 * Copyright (c) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.ims;

import static android.telephony.ims.ProvisioningManager.KEY_VOIMS_OPT_IN_STATUS;
import static android.telephony.ims.feature.MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_UT;
import static android.telephony.ims.feature.MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VIDEO;
import static android.telephony.ims.feature.MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE;
import static android.telephony.ims.feature.RcsFeature.RcsImsCapabilities.CAPABILITY_TYPE_PRESENCE_UCE;
import static android.telephony.ims.stub.ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN;
import static android.telephony.ims.stub.ImsRegistrationImplBase.REGISTRATION_TECH_LTE;

import android.annotation.NonNull;
import android.app.PendingIntent;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Message;
import android.os.PersistableBundle;
import android.os.RemoteException;
import android.os.ServiceSpecificException;
import android.os.SystemProperties;
import android.provider.Settings;
import android.telecom.TelecomManager;
import android.telephony.AccessNetworkConstants;
import android.telephony.BinderCacheManager;
import android.telephony.CarrierConfigManager;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyFrameworkInitializer;
import android.telephony.TelephonyManager;
import android.telephony.ims.ImsCallProfile;
import android.telephony.ims.ImsCallSession;
import android.telephony.ims.ImsMmTelManager;
import android.telephony.ims.ImsReasonInfo;
import android.telephony.ims.ImsService;
import android.telephony.ims.MediaQualityStatus;
import android.telephony.ims.MediaThreshold;
import android.telephony.ims.ProvisioningManager;
import android.telephony.ims.RegistrationManager;
import android.telephony.ims.RtpHeaderExtensionType;
import android.telephony.ims.SrvccCall;
import android.telephony.ims.aidl.IImsCapabilityCallback;
import android.telephony.ims.aidl.IImsConfig;
import android.telephony.ims.aidl.IImsConfigCallback;
import android.telephony.ims.aidl.IImsMmTelFeature;
import android.telephony.ims.aidl.IImsRegistration;
import android.telephony.ims.aidl.IImsRegistrationCallback;
import android.telephony.ims.aidl.IImsSmsListener;
import android.telephony.ims.aidl.ISipTransport;
import android.telephony.ims.aidl.ISrvccStartedCallback;
import android.telephony.ims.feature.CapabilityChangeRequest;
import android.telephony.ims.feature.ImsFeature;
import android.telephony.ims.feature.MmTelFeature;
import android.telephony.ims.stub.ImsCallSessionImplBase;
import android.telephony.ims.stub.ImsConfigImplBase;
import android.telephony.ims.stub.ImsRegistrationImplBase;
import android.util.SparseArray;

import com.android.ims.internal.IImsCallSession;
import com.android.ims.internal.IImsServiceFeatureCallback;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.telephony.ITelephony;
import com.android.telephony.Rlog;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

/**
 * Provides APIs for MMTEL IMS services, such as initiating IMS calls, and provides access to
 * the operator's IMS network. This class is the starting point for any IMS MMTEL actions.
 * You can acquire an instance of it with {@link #getInstance getInstance()}.
 * {Use {@link RcsFeatureManager} for RCS services}.
 * For internal use ONLY! Use {@link ImsMmTelManager} instead.
 * @hide
 */
public class ImsManager implements FeatureUpdates {

    /*
     * Debug flag to override configuration flag
     */
    public static final String PROPERTY_DBG_VOLTE_AVAIL_OVERRIDE = "persist.dbg.volte_avail_ovr";
    public static final int PROPERTY_DBG_VOLTE_AVAIL_OVERRIDE_DEFAULT = 0;
    public static final String PROPERTY_DBG_VT_AVAIL_OVERRIDE = "persist.dbg.vt_avail_ovr";
    public static final int PROPERTY_DBG_VT_AVAIL_OVERRIDE_DEFAULT = 0;
    public static final String PROPERTY_DBG_WFC_AVAIL_OVERRIDE = "persist.dbg.wfc_avail_ovr";
    public static final int PROPERTY_DBG_WFC_AVAIL_OVERRIDE_DEFAULT = 0;
    public static final String PROPERTY_DBG_ALLOW_IMS_OFF_OVERRIDE = "persist.dbg.allow_ims_off";
    public static final int PROPERTY_DBG_ALLOW_IMS_OFF_OVERRIDE_DEFAULT = 0;

    /**
     * The result code to be sent back with the incoming call {@link PendingIntent}.
     * @see #open(MmTelFeature.Listener)
     */
    public static final int INCOMING_CALL_RESULT_CODE = 101;

    /**
     * Key to retrieve the call ID from an incoming call intent. No longer used, see
     * {@link ImsCallSessionImplBase#getCallId()}.
     * @deprecated Not used in the framework, keeping around symbol to not break old vendor
     * components.
     */
    @Deprecated
    public static final String EXTRA_CALL_ID = "android:imsCallID";

    /**
     * Action to broadcast when ImsService is up.
     * Internal use only.
     * @deprecated
     * @hide
     */
    public static final String ACTION_IMS_SERVICE_UP =
            "com.android.ims.IMS_SERVICE_UP";

    /**
     * Action to broadcast when ImsService is down.
     * Internal use only.
     * @deprecated
     * @hide
     */
    public static final String ACTION_IMS_SERVICE_DOWN =
            "com.android.ims.IMS_SERVICE_DOWN";

    /**
     * Action to broadcast when ImsService registration fails.
     * Internal use only.
     * @hide
     * @deprecated use {@link android.telephony.ims.ImsManager#ACTION_WFC_IMS_REGISTRATION_ERROR}
     * instead.
     */
    @Deprecated
    public static final String ACTION_IMS_REGISTRATION_ERROR =
            android.telephony.ims.ImsManager.ACTION_WFC_IMS_REGISTRATION_ERROR;

    /**
     * Part of the ACTION_IMS_SERVICE_UP or _DOWN intents.
     * A long value; the phone ID corresponding to the IMS service coming up or down.
     * Internal use only.
     * @hide
     */
    public static final String EXTRA_PHONE_ID = "android:phone_id";

    /**
     * Action for the incoming call intent for the Phone app.
     * Internal use only.
     * @hide
     */
    public static final String ACTION_IMS_INCOMING_CALL =
            "com.android.ims.IMS_INCOMING_CALL";

    /**
     * Part of the ACTION_IMS_INCOMING_CALL intents.
     * An integer value; service identifier obtained from {@link ImsManager#open}.
     * Internal use only.
     * @hide
     * @deprecated Not used in the system, keeping around to not break old vendor components.
     */
    @Deprecated
    public static final String EXTRA_SERVICE_ID = "android:imsServiceId";

    /**
     * Part of the ACTION_IMS_INCOMING_CALL intents.
     * An boolean value; Flag to indicate that the incoming call is a normal call or call for USSD.
     * The value "true" indicates that the incoming call is for USSD.
     * Internal use only.
     * @deprecated Keeping around to not break old vendor components. Use
     * {@link MmTelFeature#EXTRA_IS_USSD} instead.
     * @hide
     */
    public static final String EXTRA_USSD = "android:ussd";

    /**
     * Part of the ACTION_IMS_INCOMING_CALL intents.
     * A boolean value; Flag to indicate whether the call is an unknown
     * dialing call. Such calls are originated by sending commands (like
     * AT commands) directly to modem without Android involvement.
     * Even though they are not incoming calls, they are propagated
     * to Phone app using same ACTION_IMS_INCOMING_CALL intent.
     * Internal use only.
     * @deprecated Keeping around to not break old vendor components. Use
     * {@link MmTelFeature#EXTRA_IS_UNKNOWN_CALL} instead.
     * @hide
     */
    public static final String EXTRA_IS_UNKNOWN_CALL = "android:isUnknown";

    private static final int SUBINFO_PROPERTY_FALSE = 0;

    private static final int SYSTEM_PROPERTY_NOT_SET = -1;

    // -1 indicates a subscriptionProperty value that is never set.
    private static final int SUB_PROPERTY_NOT_INITIALIZED = -1;

    private static final String TAG = "ImsManager";
    private static final boolean DBG = true;

    private static final int RESPONSE_WAIT_TIME_MS = 3000;

    private static final int[] LOCAL_IMS_CONFIG_KEYS = {
            KEY_VOIMS_OPT_IN_STATUS
    };

    /**
     * Create a Lazy Executor that is not instantiated for this instance unless it is used. This
     * is to stop threads from being started on ImsManagers that are created to do simple tasks.
     */
    private static class LazyExecutor implements Executor {
        private Executor mExecutor;

        @Override
        public void execute(Runnable runnable) {
            startExecutorIfNeeded();
            mExecutor.execute(runnable);
        }

        private synchronized void startExecutorIfNeeded() {
            if (mExecutor != null) return;
            mExecutor = Executors.newSingleThreadExecutor();
        }
    }

    @VisibleForTesting
    public interface MmTelFeatureConnectionFactory {
        MmTelFeatureConnection create(Context context, int phoneId, int subId,
                IImsMmTelFeature feature, IImsConfig c, IImsRegistration r, ISipTransport s);
    }

    @VisibleForTesting
    public interface SettingsProxy {
        /** @see Settings.Secure#getInt(ContentResolver, String, int) */
        int getSecureIntSetting(ContentResolver cr, String name, int def);
        /** @see Settings.Secure#putInt(ContentResolver, String, int) */
        boolean putSecureIntSetting(ContentResolver cr, String name, int value);
    }

    @VisibleForTesting
    public interface SubscriptionManagerProxy {
        boolean isValidSubscriptionId(int subId);
        int getSubscriptionId(int slotIndex);
        int getDefaultVoicePhoneId();
        int getIntegerSubscriptionProperty(int subId, String propKey, int defValue);
        void setSubscriptionProperty(int subId, String propKey, String propValue);
        int[] getActiveSubscriptionIdList();
    }

    // Default implementations, which is mocked for testing
    private static class DefaultSettingsProxy implements SettingsProxy {
        @Override
        public int getSecureIntSetting(ContentResolver cr, String name, int def) {
            return Settings.Secure.getInt(cr, name, def);
        }

        @Override
        public boolean putSecureIntSetting(ContentResolver cr, String name, int value) {
            return Settings.Secure.putInt(cr, name, value);
        }
    }

    // Default implementation which is mocked to make static dependency validation easier.
    private static class DefaultSubscriptionManagerProxy implements SubscriptionManagerProxy {

        private Context mContext;

        public DefaultSubscriptionManagerProxy(Context context) {
            mContext = context;
        }

        @Override
        public boolean isValidSubscriptionId(int subId) {
            return SubscriptionManager.isValidSubscriptionId(subId);
        }

        @Override
        public int getSubscriptionId(int slotIndex) {
            return SubscriptionManager.getSubscriptionId(slotIndex);
        }

        @Override
        public int getDefaultVoicePhoneId() {
            return SubscriptionManager.getDefaultVoicePhoneId();
        }

        @Override
        public int getIntegerSubscriptionProperty(int subId, String propKey, int defValue) {
            return SubscriptionManager.getIntegerSubscriptionProperty(subId, propKey, defValue,
                    mContext);
        }

        @Override
        public void setSubscriptionProperty(int subId, String propKey, String propValue) {
            SubscriptionManager.setSubscriptionProperty(subId, propKey, propValue);
        }

        @Override
        public int[] getActiveSubscriptionIdList() {
            return getSubscriptionManager().getActiveSubscriptionIdList();
        }

        private SubscriptionManager getSubscriptionManager() {
            return mContext.getSystemService(SubscriptionManager.class);
        }
    }

    /**
     * Events that will be triggered as part of metrics collection.
     */
    public interface ImsStatsCallback {
        /**
         * The MmTel capabilities that are enabled have changed.
         * @param capability The MmTel capability
         * @param regTech The IMS registration technology associated with the capability.
         * @param isEnabled {@code true} if the capability is enabled, {@code false} if it is
         *                  disabled.
         */
        void onEnabledMmTelCapabilitiesChanged(
                @MmTelFeature.MmTelCapabilities.MmTelCapability int capability,
                @ImsRegistrationImplBase.ImsRegistrationTech int regTech,
                boolean isEnabled);
    }

    /**
     * Internally we will create a FeatureConnector when {@link #getInstance(Context, int)} is
     * called to keep the MmTelFeatureConnection instance fresh as new SIM cards are
     * inserted/removed and MmTelFeature potentially changes.
     * <p>
     * For efficiency purposes, there is only one ImsManager created per-slot when using
     * {@link #getInstance(Context, int)} and the same instance is returned for multiple callers.
     * This is due to the ImsManager being a potentially heavyweight object depending on what it is
     * being used for.
     */
    private static class InstanceManager implements FeatureConnector.Listener<ImsManager> {
        // If this is the first time connecting, wait a small amount of time in case IMS has already
        // connected. Otherwise, ImsManager will become ready when the ImsService is connected.
        private static final int CONNECT_TIMEOUT_MS = 50;

        private final FeatureConnector<ImsManager> mConnector;
        private final ImsManager mImsManager;

        private final Object mLock = new Object();
        private boolean isConnectorActive = false;
        private CountDownLatch mConnectedLatch;

        public InstanceManager(ImsManager manager) {
            mImsManager = manager;
            // Set a special prefix so that logs generated by getInstance are distinguishable.
            mImsManager.mLogTagPostfix = "IM";

            ArrayList<Integer> readyFilter = new ArrayList<>();
            readyFilter.add(ImsFeature.STATE_READY);
            readyFilter.add(ImsFeature.STATE_INITIALIZING);
            readyFilter.add(ImsFeature.STATE_UNAVAILABLE);
            // Pass a reference of the ImsManager being managed into the connector, allowing it to
            // update the internal MmTelFeatureConnection as it is being updated.
            mConnector = new FeatureConnector<>(manager.mContext, manager.mPhoneId,
                    (c,p) -> mImsManager, "InstanceManager", readyFilter, this,
                    manager.getImsThreadExecutor());
        }

        public ImsManager getInstance() {
            return mImsManager;
        }

        public void reconnect() {
            boolean requiresReconnect = false;
            synchronized (mLock) {
                if (!isConnectorActive) {
                    requiresReconnect = true;
                    isConnectorActive = true;
                    mConnectedLatch = new CountDownLatch(1);
                }
            }
            if (requiresReconnect) {
                mConnector.connect();
            }
            try {
                // If this is during initial reconnect, let all threads wait for connect
                // (or timeout)
                if(!mConnectedLatch.await(CONNECT_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
                    mImsManager.log("ImsService not up yet - timeout waiting for connection.");
                }
            } catch (InterruptedException e) {
                // Do nothing and allow ImsService to attach behind the scenes
            }
        }

        @Override
        public void connectionReady(ImsManager manager, int subId) {
            synchronized (mLock) {
                mImsManager.logi("connectionReady, subId: " + subId);
                mConnectedLatch.countDown();
            }
        }

        @Override
        public void connectionUnavailable(int reason) {
            synchronized (mLock) {
                mImsManager.logi("connectionUnavailable, reason: " + reason);
                // only need to track the connection becoming unavailable due to telephony going
                // down.
                if (reason == FeatureConnector.UNAVAILABLE_REASON_SERVER_UNAVAILABLE) {
                    isConnectorActive = false;
                }
                mConnectedLatch.countDown();
            }

        }
    }

    // Replaced with single-threaded executor for testing.
    private final Executor mExecutor;
    // Replaced With mock for testing
    private MmTelFeatureConnectionFactory mMmTelFeatureConnectionFactory =
            MmTelFeatureConnection::new;
    private final SubscriptionManagerProxy mSubscriptionManagerProxy;
    private final SettingsProxy mSettingsProxy;

    private Context mContext;
    private CarrierConfigManager mConfigManager;
    private int mPhoneId;
    private AtomicReference<MmTelFeatureConnection> mMmTelConnectionRef = new AtomicReference<>();
    // Used for debug purposes only currently
    private boolean mConfigUpdated = false;
    private BinderCacheManager<ITelephony> mBinderCache;
    private ImsConfigListener mImsConfigListener;

    public static final String TRUE = "true";
    public static final String FALSE = "false";
    // Map of phoneId -> InstanceManager
    private static final SparseArray<InstanceManager> IMS_MANAGER_INSTANCES = new SparseArray<>(2);
    // Map of phoneId -> ImsStatsCallback
    private static final SparseArray<ImsStatsCallback> IMS_STATS_CALLBACKS = new SparseArray<>(2);

    // A log prefix added to some instances of ImsManager to make it distinguishable from others.
    // - "IM" added to ImsManager for ImsManagers created using getInstance.
    private String mLogTagPostfix = "";

    /**
     * Gets a manager instance and blocks for a limited period of time, connecting to the
     * corresponding ImsService MmTelFeature if it exists.
     * <p>
     * If the ImsService is unavailable or becomes unavailable, the associated methods will fail and
     * a new ImsManager will need to be requested. Instead, a {@link FeatureConnector} can be
     * requested using {@link #getConnector}, which will notify the caller when a new ImsManager is
     * available.
     *
     * @param context application context for creating the manager object
     * @param phoneId the phone ID for the IMS Service
     * @return the manager instance corresponding to the phoneId
     */
    @UnsupportedAppUsage
    public static ImsManager getInstance(Context context, int phoneId) {
        InstanceManager instanceManager;
        synchronized (IMS_MANAGER_INSTANCES) {
            instanceManager = IMS_MANAGER_INSTANCES.get(phoneId);
            if (instanceManager == null) {
                ImsManager m = new ImsManager(context, phoneId);
                instanceManager = new InstanceManager(m);
                IMS_MANAGER_INSTANCES.put(phoneId, instanceManager);
            }
        }
        // If the ImsManager became disconnected for some reason, try to reconnect it now.
        instanceManager.reconnect();
        return instanceManager.getInstance();
    }

    /**
     * Retrieve an FeatureConnector for ImsManager, which allows a Listener to listen for when
     * the ImsManager becomes available or unavailable due to the ImsService MmTelFeature moving to
     * the READY state or destroyed on a specific phone modem index.
     *
     * @param context The Context that will be used to connect the ImsManager.
     * @param phoneId The modem phone ID that the ImsManager will be created for.
     * @param logPrefix The log prefix used for debugging purposes.
     * @param listener The Listener that will deliver ImsManager updates as it becomes available.
     * @param executor The Executor that the Listener callbacks will be called on.
     * @return A FeatureConnector instance for generating ImsManagers as the associated
     * MmTelFeatures become available.
     */
    public static FeatureConnector<ImsManager> getConnector(Context context,
            int phoneId, String logPrefix, FeatureConnector.Listener<ImsManager> listener,
            Executor executor) {
        // Only listen for the READY state from the MmTelFeature here.
        ArrayList<Integer> readyFilter = new ArrayList<>();
        readyFilter.add(ImsFeature.STATE_READY);
        return new FeatureConnector<>(context, phoneId, ImsManager::new, logPrefix, readyFilter,
                listener, executor);
    }

    public static boolean isImsSupportedOnDevice(Context context) {
        return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY_IMS);
    }

    /**
     * Sets the callback that will be called when events related to IMS metric collection occur.
     * <p>
     * Note: Subsequent calls to this method will replace the previous stats callback.
     */
    public static void setImsStatsCallback(int phoneId, ImsStatsCallback cb) {
        synchronized (IMS_STATS_CALLBACKS) {
            if (cb == null) {
                IMS_STATS_CALLBACKS.remove(phoneId);
            } else {
                IMS_STATS_CALLBACKS.put(phoneId, cb);
            }
        }
    }

    /**
     * @return the {@link ImsStatsCallback} instance associated with the provided phoneId or
     * {@link null} if none currently exists.
     */
    private static ImsStatsCallback getStatsCallback(int phoneId) {
        synchronized (IMS_STATS_CALLBACKS) {
            return IMS_STATS_CALLBACKS.get(phoneId);
        }
    }

    /**
     * Returns the user configuration of Enhanced 4G LTE Mode setting.
     *
     * @deprecated Doesn't support MSIM devices. Use
     * {@link #isEnhanced4gLteModeSettingEnabledByUser()} instead.
     */
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
    public static boolean isEnhanced4gLteModeSettingEnabledByUser(Context context) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            return mgr.isEnhanced4gLteModeSettingEnabledByUser();
        }
        Rlog.e(TAG, "isEnhanced4gLteModeSettingEnabledByUser: ImsManager null, returning default"
                + " value.");
        return false;
    }

    /**
     * Returns the user configuration of Enhanced 4G LTE Mode setting for slot. If the option is
     * not editable ({@link CarrierConfigManager#KEY_EDITABLE_ENHANCED_4G_LTE_BOOL} is false),
     * hidden ({@link CarrierConfigManager#KEY_HIDE_ENHANCED_4G_LTE_BOOL} is true), the setting is
     * not initialized, and VoIMS opt-in status disabled, this method will return default value
     * specified by {@link CarrierConfigManager#KEY_ENHANCED_4G_LTE_ON_BY_DEFAULT_BOOL}.
     *
     * Note that even if the setting was set, it may no longer be editable. If this is the case we
     * return the default value.
     */
    public boolean isEnhanced4gLteModeSettingEnabledByUser() {
        int setting = mSubscriptionManagerProxy.getIntegerSubscriptionProperty(
                getSubId(), SubscriptionManager.ENHANCED_4G_MODE_ENABLED,
                SUB_PROPERTY_NOT_INITIALIZED);
        boolean onByDefault = getBooleanCarrierConfig(
                CarrierConfigManager.KEY_ENHANCED_4G_LTE_ON_BY_DEFAULT_BOOL);
        boolean isUiUnEditable =
                !getBooleanCarrierConfig(CarrierConfigManager.KEY_EDITABLE_ENHANCED_4G_LTE_BOOL)
                || getBooleanCarrierConfig(CarrierConfigManager.KEY_HIDE_ENHANCED_4G_LTE_BOOL);
        boolean isSettingNotInitialized = setting == SUB_PROPERTY_NOT_INITIALIZED;

        // If Enhanced 4G LTE Mode is uneditable, hidden, not initialized and VoIMS opt-in disabled
        // we use the default value. If VoIMS opt-in is enabled, we will always allow the user to
        // change the IMS enabled setting.
        if ((isUiUnEditable || isSettingNotInitialized) && !isVoImsOptInEnabled()) {
            return onByDefault;
        } else {
            return (setting == ProvisioningManager.PROVISIONING_VALUE_ENABLED);
        }
    }

    /**
     * Change persistent Enhanced 4G LTE Mode setting.
     *
     * @deprecated Doesn't support MSIM devices. Use {@link #setEnhanced4gLteModeSetting(boolean)}
     * instead.
     */
    public static void setEnhanced4gLteModeSetting(Context context, boolean enabled) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            mgr.setEnhanced4gLteModeSetting(enabled);
        }
        Rlog.e(TAG, "setEnhanced4gLteModeSetting: ImsManager null, value not set.");
    }

    /**
     * Change persistent Enhanced 4G LTE Mode setting. If the option is not editable
     * ({@link CarrierConfigManager#KEY_EDITABLE_ENHANCED_4G_LTE_BOOL} is false),
     * hidden ({@link CarrierConfigManager#KEY_HIDE_ENHANCED_4G_LTE_BOOL} is true), and VoIMS opt-in
     * status disabled, this method will set the setting to the default value specified by
     * {@link CarrierConfigManager#KEY_ENHANCED_4G_LTE_ON_BY_DEFAULT_BOOL}.
     */
    public void setEnhanced4gLteModeSetting(boolean enabled) {
        if (enabled && !isVolteProvisionedOnDevice()) {
            log("setEnhanced4gLteModeSetting: Not possible to enable VoLTE due to provisioning.");
            return;
        }
        int subId = getSubId();
        if (!isSubIdValid(subId)) {
            loge("setEnhanced4gLteModeSetting: invalid sub id, can not set property in " +
                    " siminfo db; subId=" + subId);
            return;
        }
        // If editable=false or hidden=true, we must keep default advanced 4G mode.
        boolean isUiUnEditable =
                !getBooleanCarrierConfig(CarrierConfigManager.KEY_EDITABLE_ENHANCED_4G_LTE_BOOL) ||
                        getBooleanCarrierConfig(CarrierConfigManager.KEY_HIDE_ENHANCED_4G_LTE_BOOL);

        // If VoIMS opt-in is enabled, we will always allow the user to change the IMS enabled
        // setting.
        if (isUiUnEditable && !isVoImsOptInEnabled()) {
            enabled = getBooleanCarrierConfig(
                    CarrierConfigManager.KEY_ENHANCED_4G_LTE_ON_BY_DEFAULT_BOOL);
        }

        int prevSetting = mSubscriptionManagerProxy.getIntegerSubscriptionProperty(subId,
                SubscriptionManager.ENHANCED_4G_MODE_ENABLED, SUB_PROPERTY_NOT_INITIALIZED);

        if (prevSetting == (enabled ? ProvisioningManager.PROVISIONING_VALUE_ENABLED :
                ProvisioningManager.PROVISIONING_VALUE_DISABLED)) {
            // No change in setting.
            return;
        }
        mSubscriptionManagerProxy.setSubscriptionProperty(subId,
                SubscriptionManager.ENHANCED_4G_MODE_ENABLED,
                booleanToPropertyString(enabled));
        try {
            if (enabled) {
                CapabilityChangeRequest request = new CapabilityChangeRequest();
                boolean isNonTty = isNonTtyOrTtyOnVolteEnabled();
                // This affects voice and video enablement
                updateVoiceCellFeatureValue(request, isNonTty);
                updateVideoCallFeatureValue(request, isNonTty);
                changeMmTelCapability(request);
                // Ensure IMS is on if this setting is enabled.
                turnOnIms();
            } else {
                // This may trigger entire IMS interface to be disabled, so recalculate full state.
                reevaluateCapabilities();
            }
        } catch (ImsException e) {
            loge("setEnhanced4gLteModeSetting couldn't set config: " + e);
        }
    }

    /**
     * Indicates whether the call is non-TTY or if TTY - whether TTY on VoLTE is
     * supported.
     * @deprecated Does not support MSIM devices. Please use
     * {@link #isNonTtyOrTtyOnVolteEnabled()} instead.
     */
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
    public static boolean isNonTtyOrTtyOnVolteEnabled(Context context) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            return mgr.isNonTtyOrTtyOnVolteEnabled();
        }
        Rlog.e(TAG, "isNonTtyOrTtyOnVolteEnabled: ImsManager null, returning default value.");
        return false;
    }

    /**
     * Indicates whether the call is non-TTY or if TTY - whether TTY on VoLTE is
     * supported on a per slot basis.
     */
    public boolean isNonTtyOrTtyOnVolteEnabled() {
        if (isTtyOnVoLteCapable()) {
            return true;
        }

        TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
        if (tm == null) {
            logw("isNonTtyOrTtyOnVolteEnabled: telecom not available");
            return true;
        }
        return tm.getCurrentTtyMode() == TelecomManager.TTY_MODE_OFF;
    }

    public boolean isTtyOnVoLteCapable() {
        return getBooleanCarrierConfig(CarrierConfigManager.KEY_CARRIER_VOLTE_TTY_SUPPORTED_BOOL);
    }

    /**
     * @return true if we are either not on TTY or TTY over VoWiFi is enabled. If we
     * are on TTY and TTY over VoWiFi is not allowed, this method will return false.
     */
    public boolean isNonTtyOrTtyOnVoWifiEnabled() {

        if (isTtyOnVoWifiCapable()) {
            return true;
        }

        TelecomManager tm = mContext.getSystemService(TelecomManager.class);
        if (tm == null) {
            logw("isNonTtyOrTtyOnVoWifiEnabled: telecom not available");
            return true;
        }
        return tm.getCurrentTtyMode() == TelecomManager.TTY_MODE_OFF;
    }

    public boolean isTtyOnVoWifiCapable() {
        return getBooleanCarrierConfig(CarrierConfigManager.KEY_CARRIER_VOWIFI_TTY_SUPPORTED_BOOL);
    }

    /**
     * Returns a platform configuration for VoLTE which may override the user setting.
     * @deprecated Does not support MSIM devices. Please use
     * {@link #isVolteEnabledByPlatform()} instead.
     */
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
    public static boolean isVolteEnabledByPlatform(Context context) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            return mgr.isVolteEnabledByPlatform();
        }
        Rlog.e(TAG, "isVolteEnabledByPlatform: ImsManager null, returning default value.");
        return false;
    }

    /**
     * Asynchronous call to ImsService to determine whether or not a specific MmTel capability is
     * supported.
     */
    public void isSupported(int capability, int transportType, Consumer<Boolean> result) {
        getImsThreadExecutor().execute(() -> {
            switch(transportType) {
                // Does not take into account NR, as NR is a superset of LTE support currently.
                case (AccessNetworkConstants.TRANSPORT_TYPE_WWAN): {
                    switch (capability) {
                        case (MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE): {
                            result.accept(isVolteEnabledByPlatform());
                            return;
                        } case (MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VIDEO): {
                            result.accept(isVtEnabledByPlatform());
                            return;
                        }case (MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_UT): {
                            result.accept(isSuppServicesOverUtEnabledByPlatform());
                            return;
                        } case (MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_SMS): {
                            // There is currently no carrier config defined for this.
                            result.accept(true);
                            return;
                        }
                    }
                    break;
                } case (AccessNetworkConstants.TRANSPORT_TYPE_WLAN): {
                    switch (capability) {
                        case (MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE) : {
                            result.accept(isWfcEnabledByPlatform());
                            return;
                        } case (MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VIDEO) : {
                            // This is not transport dependent at this time.
                            result.accept(isVtEnabledByPlatform());
                            return;
                        } case (MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_UT) : {
                            // This is not transport dependent at this time.
                            result.accept(isSuppServicesOverUtEnabledByPlatform());
                            return;
                        } case (MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_SMS) : {
                            // There is currently no carrier config defined for this.
                            result.accept(true);
                            return;
                        }
                    }
                    break;
                }
            }
            // false for unknown capability/transport types.
            result.accept(false);
        });

    }

    /**
     * Returns a platform configuration for VoLTE which may override the user setting on a per Slot
     * basis.
     */
    public boolean isVolteEnabledByPlatform() {
        // We first read the per slot value. If doesn't exist, we read the general value. If still
        // doesn't exist, we use the hardcoded default value.
        if (SystemProperties.getInt(
                PROPERTY_DBG_VOLTE_AVAIL_OVERRIDE + Integer.toString(mPhoneId),
                SYSTEM_PROPERTY_NOT_SET) == 1 ||
                SystemProperties.getInt(PROPERTY_DBG_VOLTE_AVAIL_OVERRIDE,
                        SYSTEM_PROPERTY_NOT_SET) == 1) {
            return true;
        }

        if (getLocalImsConfigKeyInt(KEY_VOIMS_OPT_IN_STATUS)
                == ProvisioningManager.PROVISIONING_VALUE_ENABLED) {
            return true;
        }

        return mContext.getResources().getBoolean(
                com.android.internal.R.bool.config_device_volte_available)
                && getBooleanCarrierConfig(CarrierConfigManager.KEY_CARRIER_VOLTE_AVAILABLE_BOOL)
                && isGbaValid();
    }

    /**
     * @return {@code true} if IMS over NR is enabled by the platform, {@code false} otherwise.
     */
    public boolean isImsOverNrEnabledByPlatform() {
        int[] nrCarrierCaps = getIntArrayCarrierConfig(
                CarrierConfigManager.KEY_CARRIER_NR_AVAILABILITIES_INT_ARRAY);
        if (nrCarrierCaps == null)  return false;
        boolean voNrCarrierSupported = Arrays.stream(nrCarrierCaps)
                .anyMatch(cap -> cap == CarrierConfigManager.CARRIER_NR_AVAILABILITY_SA);
        if (!voNrCarrierSupported) return false;
        return isGbaValid();
    }

    /**
     * Indicates whether VoLTE is provisioned on device.
     *
     * @deprecated Does not support MSIM devices. Please use
     * {@link #isVolteProvisionedOnDevice()} instead.
     */
    public static boolean isVolteProvisionedOnDevice(Context context) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            return mgr.isVolteProvisionedOnDevice();
        }
        Rlog.e(TAG, "isVolteProvisionedOnDevice: ImsManager null, returning default value.");
        return true;
    }

    /**
     * Indicates whether VoLTE is provisioned on this slot.
     */
    public boolean isVolteProvisionedOnDevice() {
        if (isMmTelProvisioningRequired(CAPABILITY_TYPE_VOICE, REGISTRATION_TECH_LTE)) {
            return isVolteProvisioned();
        }

        return true;
    }

    /**
     * Indicates whether EAB is provisioned on this slot.
     */
    public boolean isEabProvisionedOnDevice() {
        if (isRcsProvisioningRequired(CAPABILITY_TYPE_PRESENCE_UCE, REGISTRATION_TECH_LTE)) {
            return isEabProvisioned();
        }

        return true;
    }

    /**
     * Indicates whether VoWifi is provisioned on device.
     *
     * When CarrierConfig KEY_CARRIER_VOLTE_OVERRIDE_WFC_PROVISIONING_BOOL is true, and VoLTE is not
     * provisioned on device, this method returns false.
     *
     * @deprecated Does not support MSIM devices. Please use
     * {@link #isWfcProvisionedOnDevice()} instead.
     */
    public static boolean isWfcProvisionedOnDevice(Context context) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            return mgr.isWfcProvisionedOnDevice();
        }
        Rlog.e(TAG, "isWfcProvisionedOnDevice: ImsManager null, returning default value.");
        return true;
    }

    /**
     * Indicates whether VoWifi is provisioned on slot.
     *
     * When CarrierConfig KEY_CARRIER_VOLTE_OVERRIDE_WFC_PROVISIONING_BOOL is true, and VoLTE is not
     * provisioned on device, this method returns false.
     */
    public boolean isWfcProvisionedOnDevice() {
        if (getBooleanCarrierConfig(
                CarrierConfigManager.KEY_CARRIER_VOLTE_OVERRIDE_WFC_PROVISIONING_BOOL)) {
            if (!isVolteProvisionedOnDevice()) {
                return false;
            }
        }

        if (isMmTelProvisioningRequired(CAPABILITY_TYPE_VOICE, REGISTRATION_TECH_IWLAN)) {
            return isWfcProvisioned();
        }

        return true;
    }

    /**
     * Indicates whether VT is provisioned on device
     *
     * @deprecated Does not support MSIM devices. Please use
     * {@link #isVtProvisionedOnDevice()} instead.
     */
    public static boolean isVtProvisionedOnDevice(Context context) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            return mgr.isVtProvisionedOnDevice();
        }
        Rlog.e(TAG, "isVtProvisionedOnDevice: ImsManager null, returning default value.");
        return true;
    }

    /**
     * Indicates whether VT is provisioned on slot.
     */
    public boolean isVtProvisionedOnDevice() {
        if (isMmTelProvisioningRequired(CAPABILITY_TYPE_VIDEO, REGISTRATION_TECH_LTE)) {
            return isVtProvisioned();
        }

        return true;
    }

    /**
     * Returns a platform configuration for VT which may override the user setting.
     *
     * Note: VT presumes that VoLTE is enabled (these are configuration settings
     * which must be done correctly).
     *
     * @deprecated Does not support MSIM devices. Please use
     * {@link #isVtEnabledByPlatform()} instead.
     */
    public static boolean isVtEnabledByPlatform(Context context) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            return mgr.isVtEnabledByPlatform();
        }
        Rlog.e(TAG, "isVtEnabledByPlatform: ImsManager null, returning default value.");
        return false;
    }

    /**
     * Returns a platform configuration for VT which may override the user setting.
     *
     * Note: VT presumes that VoLTE is enabled (these are configuration settings
     * which must be done correctly).
     */
    public boolean isVtEnabledByPlatform() {
        // We first read the per slot value. If doesn't exist, we read the general value. If still
        // doesn't exist, we use the hardcoded default value.
        if (SystemProperties.getInt(PROPERTY_DBG_VT_AVAIL_OVERRIDE +
                Integer.toString(mPhoneId), SYSTEM_PROPERTY_NOT_SET) == 1  ||
                SystemProperties.getInt(
                        PROPERTY_DBG_VT_AVAIL_OVERRIDE, SYSTEM_PROPERTY_NOT_SET) == 1) {
            return true;
        }

        return mContext.getResources().getBoolean(
                com.android.internal.R.bool.config_device_vt_available) &&
                getBooleanCarrierConfig(CarrierConfigManager.KEY_CARRIER_VT_AVAILABLE_BOOL) &&
                isGbaValid();
    }

    /**
     * Returns the user configuration of VT setting
     * @deprecated Does not support MSIM devices. Please use
     * {@link #isVtEnabledByUser()} instead.
     */
    public static boolean isVtEnabledByUser(Context context) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            return mgr.isVtEnabledByUser();
        }
        Rlog.e(TAG, "isVtEnabledByUser: ImsManager null, returning default value.");
        return false;
    }

    /**
     * Returns the user configuration of VT setting per slot. If not set, it
     * returns true as default value.
     */
    public boolean isVtEnabledByUser() {
        int setting = mSubscriptionManagerProxy.getIntegerSubscriptionProperty(
                getSubId(), SubscriptionManager.VT_IMS_ENABLED,
                SUB_PROPERTY_NOT_INITIALIZED);

        // If it's never set, by default we return true.
        return (setting == SUB_PROPERTY_NOT_INITIALIZED
                || setting == ProvisioningManager.PROVISIONING_VALUE_ENABLED);
    }

    /**
     * Returns whether the user sets call composer setting per sub.
     */
    public boolean isCallComposerEnabledByUser() {
        TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
        if (tm == null) {
            loge("isCallComposerEnabledByUser: TelephonyManager is null, returning false");
            return false;
        }
        return tm.getCallComposerStatus() == TelephonyManager.CALL_COMPOSER_STATUS_ON;
    }

    /**
     * Change persistent VT enabled setting
     *
     * @deprecated Does not support MSIM devices. Please use {@link #setVtSetting(boolean)} instead.
     */
    public static void setVtSetting(Context context, boolean enabled) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            mgr.setVtSetting(enabled);
        }
        Rlog.e(TAG, "setVtSetting: ImsManager null, can not set value.");
    }

    /**
     * Change persistent VT enabled setting for slot.
     */
    public void setVtSetting(boolean enabled) {
        if (enabled && !isVtProvisionedOnDevice()) {
            log("setVtSetting: Not possible to enable Vt due to provisioning.");
            return;
        }

        int subId = getSubId();
        if (!isSubIdValid(subId)) {
            loge("setVtSetting: sub id invalid, skip modifying vt state in subinfo db; subId="
                    + subId);
            return;
        }
        mSubscriptionManagerProxy.setSubscriptionProperty(subId, SubscriptionManager.VT_IMS_ENABLED,
                booleanToPropertyString(enabled));
        try {
            if (enabled) {
                CapabilityChangeRequest request = new CapabilityChangeRequest();
                updateVideoCallFeatureValue(request, isNonTtyOrTtyOnVolteEnabled());
                changeMmTelCapability(request);
                // ensure IMS is enabled.
                turnOnIms();
            } else {
                // This may cause IMS to be disabled, re-evaluate all.
                reevaluateCapabilities();
            }
        } catch (ImsException e) {
            // The ImsService is down. Since the SubscriptionManager already recorded the user's
            // preference, it will be resent in updateImsServiceConfig when the ImsPhoneCallTracker
            // reconnects.
            loge("setVtSetting(b): ", e);
        }
    }

    /**
     * Returns whether turning off ims is allowed by platform.
     * The platform property may override the carrier config.
     */
    private boolean isTurnOffImsAllowedByPlatform() {
        // We first read the per slot value. If doesn't exist, we read the general value. If still
        // doesn't exist, we use the hardcoded default value.
        if (SystemProperties.getInt(PROPERTY_DBG_ALLOW_IMS_OFF_OVERRIDE +
                Integer.toString(mPhoneId), SYSTEM_PROPERTY_NOT_SET) == 1  ||
                SystemProperties.getInt(
                        PROPERTY_DBG_ALLOW_IMS_OFF_OVERRIDE, SYSTEM_PROPERTY_NOT_SET) == 1) {
            return true;
        }

        return getBooleanCarrierConfig(
                CarrierConfigManager.KEY_CARRIER_ALLOW_TURNOFF_IMS_BOOL);
    }

    /**
     * Returns the user configuration of WFC setting
     *
     * @deprecated Does not support MSIM devices. Please use
     * {@link #isWfcEnabledByUser()} instead.
     */
    public static boolean isWfcEnabledByUser(Context context) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            return mgr.isWfcEnabledByUser();
        }
        Rlog.e(TAG, "isWfcEnabledByUser: ImsManager null, returning default value.");
        return true;
    }

    /**
     * Returns the user configuration of WFC setting for slot. If not set, it
     * queries CarrierConfig value as default.
     */
    public boolean isWfcEnabledByUser() {
        int setting = mSubscriptionManagerProxy.getIntegerSubscriptionProperty(
                getSubId(), SubscriptionManager.WFC_IMS_ENABLED,
                SUB_PROPERTY_NOT_INITIALIZED);

        // SUB_PROPERTY_NOT_INITIALIZED indicates it's never set in sub db.
        if (setting == SUB_PROPERTY_NOT_INITIALIZED) {
            return getBooleanCarrierConfig(
                    CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ENABLED_BOOL);
        } else {
            return setting == ProvisioningManager.PROVISIONING_VALUE_ENABLED;
        }
    }

    /**
     * Change persistent WFC enabled setting.
     * @deprecated Does not support MSIM devices. Please use
     * {@link #setWfcSetting} instead.
     */
    public static void setWfcSetting(Context context, boolean enabled) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            mgr.setWfcSetting(enabled);
        }
        Rlog.e(TAG, "setWfcSetting: ImsManager null, can not set value.");
    }

    /**
     * Change persistent WFC enabled setting for slot.
     */
    public void setWfcSetting(boolean enabled) {
        if (enabled && !isWfcProvisionedOnDevice()) {
            log("setWfcSetting: Not possible to enable WFC due to provisioning.");
            return;
        }
        int subId = getSubId();
        if (!isSubIdValid(subId)) {
            loge("setWfcSetting: invalid sub id, can not set WFC setting in siminfo db; subId="
                    + subId);
            return;
        }
        mSubscriptionManagerProxy.setSubscriptionProperty(subId,
                SubscriptionManager.WFC_IMS_ENABLED, booleanToPropertyString(enabled));

        try {
            if (enabled) {
                boolean isNonTtyWifi = isNonTtyOrTtyOnVoWifiEnabled();
                CapabilityChangeRequest request = new CapabilityChangeRequest();
                updateVoiceWifiFeatureAndProvisionedValues(request, isNonTtyWifi);
                changeMmTelCapability(request);
                // Ensure IMS is on if this setting is updated.
                turnOnIms();
            } else {
                // This may cause IMS to be disabled, re-evaluate all caps
                reevaluateCapabilities();
            }
        } catch (ImsException e) {
            loge("setWfcSetting: " + e);
        }
    }

    /**
     * @return true if the user's setting for Voice over Cross SIM is enabled and
     * false if it is not
     */
    public boolean isCrossSimCallingEnabledByUser() {
        int setting = mSubscriptionManagerProxy.getIntegerSubscriptionProperty(
                getSubId(), SubscriptionManager.CROSS_SIM_CALLING_ENABLED,
                SUB_PROPERTY_NOT_INITIALIZED);

        // SUB_PROPERTY_NOT_INITIALIZED indicates it's never set in sub db.
        if (setting == SUB_PROPERTY_NOT_INITIALIZED) {
            return false;
        } else {
            return setting == ProvisioningManager.PROVISIONING_VALUE_ENABLED;
        }
    }

    /**
     * @return true if Voice over Cross SIM is provisioned and enabled by user and platform.
     * false if any of them is not true
     */
    public boolean isCrossSimCallingEnabled() {
        boolean userEnabled = isCrossSimCallingEnabledByUser();
        boolean platformEnabled = isCrossSimEnabledByPlatform();
        boolean isProvisioned = isWfcProvisionedOnDevice();

        log("isCrossSimCallingEnabled: platformEnabled = " + platformEnabled
                + ", provisioned = " + isProvisioned
                + ", userEnabled = " + userEnabled);
        return userEnabled && platformEnabled && isProvisioned;
    }

    /**
     * Sets the user's setting for whether or not Voice over Cross SIM is enabled.
     */
    public void setCrossSimCallingEnabled(boolean enabled) {
        if (enabled && !isWfcProvisionedOnDevice()) {
            log("setCrossSimCallingEnabled: Not possible to enable WFC due to provisioning.");
            return;
        }
        int subId = getSubId();
        if (!isSubIdValid(subId)) {
            loge("setCrossSimCallingEnabled: "
                    + "invalid sub id, can not set Cross SIM setting in siminfo db; subId="
                    + subId);
            return;
        }
        mSubscriptionManagerProxy.setSubscriptionProperty(subId,
                SubscriptionManager.CROSS_SIM_CALLING_ENABLED, booleanToPropertyString(enabled));
        try {
            if (enabled) {
                CapabilityChangeRequest request = new CapabilityChangeRequest();
                updateCrossSimFeatureAndProvisionedValues(request);
                changeMmTelCapability(request);
                turnOnIms();
            } else {
                // Recalculate all caps to determine if IMS needs to be disabled.
                reevaluateCapabilities();
            }
        } catch (ImsException e) {
            loge("setCrossSimCallingEnabled(): ", e);
        }
    }

    /**
     * Non-persistently change WFC enabled setting and WFC mode for slot
     *
     * @param enabled If true, WFC and WFC while roaming will be enabled for the associated
     *                subscription, if supported by the carrier. If false, WFC will be disabled for
     *                the associated subscription.
     * @param wfcMode The WFC preference if WFC is enabled
     */
    public void setWfcNonPersistent(boolean enabled, int wfcMode) {
        // Force IMS to register over LTE when turning off WFC
        int imsWfcModeFeatureValue =
                enabled ? wfcMode : ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED;
        try {
            changeMmTelCapability(enabled, MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
                    ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN);
            // Set the mode and roaming enabled settings before turning on IMS
            setWfcModeInternal(imsWfcModeFeatureValue);
            // If enabled is false, shortcut to false because of the ImsService
            // implementation for WFC roaming, otherwise use the correct user's setting.
            setWfcRoamingSettingInternal(enabled && isWfcRoamingEnabledByUser());
            // Do not re-evaluate all capabilities because this is a temporary override of WFC
            // settings.
            if (enabled) {
                log("setWfcNonPersistent() : turnOnIms");
                // Ensure IMS is turned on if this is enabled.
                turnOnIms();
            }
        } catch (ImsException e) {
            loge("setWfcNonPersistent(): ", e);
        }
    }

    /**
     * Returns the user configuration of WFC preference setting.
     *
     * @deprecated Doesn't support MSIM devices. Use {@link #getWfcMode(boolean roaming)} instead.
     */
    public static int getWfcMode(Context context) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            return mgr.getWfcMode();
        }
        Rlog.e(TAG, "getWfcMode: ImsManager null, returning default value.");
        return ImsMmTelManager.WIFI_MODE_WIFI_ONLY;
    }

    /**
     * Returns the user configuration of WFC preference setting
     * @deprecated. Use {@link #getWfcMode(boolean roaming)} instead.
     */
    public int getWfcMode() {
        return getWfcMode(false);
    }

    /**
     * Change persistent WFC preference setting.
     *
     * @deprecated Doesn't support MSIM devices. Use {@link #setWfcMode(int)} instead.
     */
    public static void setWfcMode(Context context, int wfcMode) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            mgr.setWfcMode(wfcMode);
        }
        Rlog.e(TAG, "setWfcMode: ImsManager null, can not set value.");
    }

    /**
     * Change persistent WFC preference setting for slot when not roaming.
     * @deprecated Use {@link #setWfcMode(int, boolean)} instead.
     */
    public void setWfcMode(int wfcMode) {
        setWfcMode(wfcMode, false /*isRoaming*/);
    }

    /**
     * Returns the user configuration of WFC preference setting
     *
     * @param roaming {@code false} for home network setting, {@code true} for roaming  setting
     *
     * @deprecated Doesn't support MSIM devices. Use {@link #getWfcMode(boolean)} instead.
     */
    public static int getWfcMode(Context context, boolean roaming) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            return mgr.getWfcMode(roaming);
        }
        Rlog.e(TAG, "getWfcMode: ImsManager null, returning default value.");
        return ImsMmTelManager.WIFI_MODE_WIFI_ONLY;
    }

    /**
     * Returns the user configuration of WFC preference setting for slot. If not set, it
     * queries CarrierConfig value as default.
     *
     * @param roaming {@code false} for home network setting, {@code true} for roaming  setting
     */
    public int getWfcMode(boolean roaming) {
        int setting;
        if (!roaming) {
            // The WFC mode is not editable, return the default setting in the CarrierConfig, not
            // the user set value.
            if (!getBooleanCarrierConfig(CarrierConfigManager.KEY_EDITABLE_WFC_MODE_BOOL)) {
                setting = getIntCarrierConfig(
                        CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_MODE_INT);

            } else {
                setting = getSettingFromSubscriptionManager(SubscriptionManager.WFC_IMS_MODE,
                        CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_MODE_INT);
            }
            if (DBG) log("getWfcMode - setting=" + setting);
        } else {
            if (getBooleanCarrierConfig(
                    CarrierConfigManager.KEY_USE_WFC_HOME_NETWORK_MODE_IN_ROAMING_NETWORK_BOOL)) {
                setting = getWfcMode(false);
            } else if (!getBooleanCarrierConfig(
                    CarrierConfigManager.KEY_EDITABLE_WFC_ROAMING_MODE_BOOL)) {
                setting = getIntCarrierConfig(
                        CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_MODE_INT);
            } else {
                setting = getSettingFromSubscriptionManager(
                        SubscriptionManager.WFC_IMS_ROAMING_MODE,
                        CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_MODE_INT);
            }
            if (DBG) log("getWfcMode (roaming) - setting=" + setting);
        }
        return setting;
    }

    /**
     * Returns the SubscriptionManager setting for the subSetting string. If it is not set, default
     * to the default CarrierConfig value for defaultConfigKey.
     */
    private int getSettingFromSubscriptionManager(String subSetting, String defaultConfigKey) {
        int result;
        result = mSubscriptionManagerProxy.getIntegerSubscriptionProperty(getSubId(), subSetting,
                SUB_PROPERTY_NOT_INITIALIZED);

        // SUB_PROPERTY_NOT_INITIALIZED indicates it's never set in sub db.
        if (result == SUB_PROPERTY_NOT_INITIALIZED) {
            result = getIntCarrierConfig(defaultConfigKey);
        }
        return result;
    }

    /**
     * Change persistent WFC preference setting
     *
     * @param roaming {@code false} for home network setting, {@code true} for roaming setting
     *
     * @deprecated Doesn't support MSIM devices. Please use {@link #setWfcMode(int, boolean)}
     * instead.
     */
    public static void setWfcMode(Context context, int wfcMode, boolean roaming) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            mgr.setWfcMode(wfcMode, roaming);
        }
        Rlog.e(TAG, "setWfcMode: ImsManager null, can not set value.");
    }

    /**
     * Change persistent WFC preference setting
     *
     * @param roaming {@code false} for home network setting, {@code true} for roaming setting
     */
    public void setWfcMode(int wfcMode, boolean roaming) {
        int subId = getSubId();
        if (isSubIdValid(subId)) {
            if (!roaming) {
                if (DBG) log("setWfcMode(i,b) - setting=" + wfcMode);
                mSubscriptionManagerProxy.setSubscriptionProperty(subId, SubscriptionManager.WFC_IMS_MODE,
                        Integer.toString(wfcMode));
            } else {
                if (DBG) log("setWfcMode(i,b) (roaming) - setting=" + wfcMode);
                mSubscriptionManagerProxy.setSubscriptionProperty(subId,
                        SubscriptionManager.WFC_IMS_ROAMING_MODE, Integer.toString(wfcMode));
            }
        } else {
            loge("setWfcMode(i,b): invalid sub id, skip setting setting in siminfo db; subId="
                    + subId);
        }

        TelephonyManager tm = (TelephonyManager)
                mContext.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm == null) {
            loge("setWfcMode: TelephonyManager is null, can not set WFC.");
            return;
        }
        tm = tm.createForSubscriptionId(getSubId());
        // Unfortunately, the WFC mode is the same for home/roaming (we do not have separate
        // config keys), so we have to change the WFC mode when moving home<->roaming. So, only
        // call setWfcModeInternal when roaming == telephony roaming status. Otherwise, ignore.
        if (roaming == tm.isNetworkRoaming()) {
            setWfcModeInternal(wfcMode);
        }
    }

    private int getSubId() {
        return mSubscriptionManagerProxy.getSubscriptionId(mPhoneId);
    }

    private void setWfcModeInternal(int wfcMode) {
        final int value = wfcMode;
        getImsThreadExecutor().execute(() -> {
            try {
                getConfigInterface().setConfig(
                        ProvisioningManager.KEY_VOICE_OVER_WIFI_MODE_OVERRIDE, value);
            } catch (ImsException e) {
                // do nothing
            }
        });
    }

    /**
     * Returns the user configuration of WFC roaming setting
     *
     * @deprecated Does not support MSIM devices. Please use
     * {@link #isWfcRoamingEnabledByUser()} instead.
     */
    public static boolean isWfcRoamingEnabledByUser(Context context) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            return mgr.isWfcRoamingEnabledByUser();
        }
        Rlog.e(TAG, "isWfcRoamingEnabledByUser: ImsManager null, returning default value.");
        return false;
    }

    /**
     * Returns the user configuration of WFC roaming setting for slot. If not set, it
     * queries CarrierConfig value as default.
     */
    public boolean isWfcRoamingEnabledByUser() {
        int setting =  mSubscriptionManagerProxy.getIntegerSubscriptionProperty(
                getSubId(), SubscriptionManager.WFC_IMS_ROAMING_ENABLED,
                SUB_PROPERTY_NOT_INITIALIZED);
        if (setting == SUB_PROPERTY_NOT_INITIALIZED) {
            return getBooleanCarrierConfig(
                            CarrierConfigManager.KEY_CARRIER_DEFAULT_WFC_IMS_ROAMING_ENABLED_BOOL);
        } else {
            return setting == ProvisioningManager.PROVISIONING_VALUE_ENABLED;
        }
    }

    /**
     * Change persistent WFC roaming enabled setting
     */
    public static void setWfcRoamingSetting(Context context, boolean enabled) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            mgr.setWfcRoamingSetting(enabled);
        }
        Rlog.e(TAG, "setWfcRoamingSetting: ImsManager null, value not set.");
    }

    /**
     * Change persistent WFC roaming enabled setting
     */
    public void setWfcRoamingSetting(boolean enabled) {
        mSubscriptionManagerProxy.setSubscriptionProperty(getSubId(),
                SubscriptionManager.WFC_IMS_ROAMING_ENABLED, booleanToPropertyString(enabled)
        );

        setWfcRoamingSettingInternal(enabled);
    }

    private void setWfcRoamingSettingInternal(boolean enabled) {
        final int value = enabled
                ? ProvisioningManager.PROVISIONING_VALUE_ENABLED
                : ProvisioningManager.PROVISIONING_VALUE_DISABLED;
        getImsThreadExecutor().execute(() -> {
            try {
                getConfigInterface().setConfig(
                        ProvisioningManager.KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE, value);
            } catch (ImsException e) {
                // do nothing
            }
        });
    }

    /**
     * Returns a platform configuration for WFC which may override the user
     * setting. Note: WFC presumes that VoLTE is enabled (these are
     * configuration settings which must be done correctly).
     *
     * @deprecated Doesn't work for MSIM devices. Use {@link #isWfcEnabledByPlatform()}
     * instead.
     */
    public static boolean isWfcEnabledByPlatform(Context context) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            return mgr.isWfcEnabledByPlatform();
        }
        Rlog.e(TAG, "isWfcEnabledByPlatform: ImsManager null, returning default value.");
        return false;
    }

    /**
     * Returns a platform configuration for WFC which may override the user
     * setting per slot. Note: WFC presumes that VoLTE is enabled (these are
     * configuration settings which must be done correctly).
     */
    public boolean isWfcEnabledByPlatform() {
        // We first read the per slot value. If doesn't exist, we read the general value. If still
        // doesn't exist, we use the hardcoded default value.
        if (SystemProperties.getInt(PROPERTY_DBG_WFC_AVAIL_OVERRIDE +
                Integer.toString(mPhoneId), SYSTEM_PROPERTY_NOT_SET) == 1  ||
                SystemProperties.getInt(
                        PROPERTY_DBG_WFC_AVAIL_OVERRIDE, SYSTEM_PROPERTY_NOT_SET) == 1) {
            return true;
        }

        return mContext.getResources().getBoolean(
                com.android.internal.R.bool.config_device_wfc_ims_available) &&
                getBooleanCarrierConfig(
                        CarrierConfigManager.KEY_CARRIER_WFC_IMS_AVAILABLE_BOOL) &&
                isGbaValid();
    }

    /**
     * Returns a platform configuration for Cross SIM which may override the user
     * setting per slot. Note: Cross SIM presumes that VoLTE is enabled (these are
     * configuration settings which must be done correctly).
     */
    public boolean isCrossSimEnabledByPlatform() {
        if (isWfcEnabledByPlatform()) {
            return getBooleanCarrierConfig(
                    CarrierConfigManager.KEY_CARRIER_CROSS_SIM_IMS_AVAILABLE_BOOL);
        }
        return false;
    }

    public boolean isSuppServicesOverUtEnabledByPlatform() {
        TelephonyManager manager = (TelephonyManager) mContext.getSystemService(
                Context.TELEPHONY_SERVICE);
        int cardState = manager.getSimState(mPhoneId);
        if (cardState != TelephonyManager.SIM_STATE_READY) {
            // Do not report enabled until we actually have an active subscription.
            return false;
        }
        return getBooleanCarrierConfig(CarrierConfigManager.KEY_CARRIER_SUPPORTS_SS_OVER_UT_BOOL) &&
                isGbaValid();
    }

    /**
     * If carrier requires that IMS is only available if GBA capable SIM is used,
     * then this function checks GBA bit in EF IST.
     *
     * Format of EF IST is defined in 3GPP TS 31.103 (Section 4.2.7).
     */
    private boolean isGbaValid() {
        if (getBooleanCarrierConfig(
                CarrierConfigManager.KEY_CARRIER_IMS_GBA_REQUIRED_BOOL)) {
            TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
            if (tm == null) {
                loge("isGbaValid: TelephonyManager is null, returning false.");
                return false;
            }
            tm = tm.createForSubscriptionId(getSubId());
            String efIst = tm.getIsimIst();
            if (efIst == null) {
                loge("isGbaValid - ISF is NULL");
                return true;
            }
            boolean result = efIst != null && efIst.length() > 1 &&
                    (0x02 & (byte)efIst.charAt(1)) != 0;
            if (DBG) log("isGbaValid - GBA capable=" + result + ", ISF=" + efIst);
            return result;
        }
        return true;
    }

    /**
     * Will return with MmTel config value or return false if we receive an error from the AOSP
     * storage(ImsProvisioningController) implementation for that value.
     */
    private boolean getImsProvisionedBoolNoException(int capability, int tech) {
        int subId = getSubId();
        if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
            logw("getImsProvisionedBoolNoException subId is invalid");
            return false;
        }

        ITelephony iTelephony = getITelephony();
        if (iTelephony == null) {
            logw("getImsProvisionedBoolNoException ITelephony interface is invalid");
            return false;
        }

        try {
            return iTelephony.getImsProvisioningStatusForCapability(subId, capability, tech);
        } catch (RemoteException | IllegalArgumentException e) {
            logw("getImsProvisionedBoolNoException: operation failed for capability=" + capability
                    + ". Exception:" + e.getMessage() + ". Returning false.");
            return false;
        }
    }

    /**
     * Will return with Rcs config value or return false if we receive an error from the AOSP
     * storage(ImsProvisioningController) implementation for that value.
     */
    private boolean getRcsProvisionedBoolNoException(int capability, int tech) {
        int subId = getSubId();
        if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
            logw("getRcsProvisionedBoolNoException subId is invalid");
            return false;
        }

        ITelephony iTelephony = getITelephony();
        if (iTelephony == null) {
            logw("getRcsProvisionedBoolNoException ITelephony interface is invalid");
            return false;
        }

        try {
            return iTelephony.getRcsProvisioningStatusForCapability(subId, capability, tech);
        } catch (RemoteException | IllegalArgumentException e) {
            logw("getRcsProvisionedBoolNoException: operation failed for capability=" + capability
                    + ". Exception:" + e.getMessage() + ". Returning false.");
            return false;
        }
    }

    /**
     * Push configuration updates to the ImsService implementation.
     */
    public void updateImsServiceConfig() {
        try {
            int subId = getSubId();
            if (!isSubIdValid(subId)) {
                loge("updateImsServiceConfig: invalid sub id, skipping!");
                return;
            }
            PersistableBundle imsCarrierConfigs =
                    mConfigManager.getConfigByComponentForSubId(
                            CarrierConfigManager.Ims.KEY_PREFIX, subId);
            updateImsCarrierConfigs(imsCarrierConfigs);
            reevaluateCapabilities();
            mConfigUpdated = true;
        } catch (ImsException e) {
            loge("updateImsServiceConfig: ", e);
            mConfigUpdated = false;
        }
    }

    /**
     * Evaluate the state of the IMS capabilities and push the updated state to the ImsService.
     */
    private void reevaluateCapabilities() throws ImsException {
        logi("reevaluateCapabilities");
        CapabilityChangeRequest request = new CapabilityChangeRequest();
        boolean isNonTty = isNonTtyOrTtyOnVolteEnabled();
        boolean isNonTtyWifi = isNonTtyOrTtyOnVoWifiEnabled();
        updateVoiceCellFeatureValue(request, isNonTty);
        updateVoiceWifiFeatureAndProvisionedValues(request, isNonTtyWifi);
        updateCrossSimFeatureAndProvisionedValues(request);
        updateVideoCallFeatureValue(request, isNonTty);
        updateCallComposerFeatureValue(request);
        // Only turn on IMS for RTT if there's an active subscription present. If not, the
        // modem will be in emergency-call-only mode and will use separate signaling to
        // establish an RTT emergency call.
        boolean isImsNeededForRtt = updateRttConfigValue() && isActiveSubscriptionPresent();
        // Supplementary services over UT do not require IMS registration. Do not alter IMS
        // registration based on UT.
        updateUtFeatureValue(request);

        // Send the batched request to the modem.
        changeMmTelCapability(request);

        if (isImsNeededForRtt || !isTurnOffImsAllowedByPlatform() || isImsNeeded(request)) {
            // Turn on IMS if it is used.
            // Also, if turning off is not allowed for current carrier,
            // we need to turn IMS on because it might be turned off before
            // phone switched to current carrier.
            log("reevaluateCapabilities: turnOnIms");
            turnOnIms();
        } else {
            // Turn off IMS if it is not used AND turning off is allowed for carrier.
            log("reevaluateCapabilities: turnOffIms");
            turnOffIms();
        }
    }

    /**
     * @return {@code true} if IMS needs to be turned on for the request, {@code false} if it can
     * be disabled.
     */
    private boolean isImsNeeded(CapabilityChangeRequest r) {
        return r.getCapabilitiesToEnable().stream()
                .anyMatch(c -> isImsNeededForCapability(c.getCapability()));
    }

    /**
     * @return {@code true} if IMS needs to be turned on for the capability.
     */
    private boolean isImsNeededForCapability(int capability) {
        // UT does not require IMS to be enabled.
        return capability != MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_UT &&
                // call composer is used as part of calling, so it should not trigger the enablement
                // of IMS.
                capability != MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_CALL_COMPOSER;
    }

    /**
     * Update VoLTE config
     */
    private void updateVoiceCellFeatureValue(CapabilityChangeRequest request, boolean isNonTty) {
        boolean available = isVolteEnabledByPlatform();
        boolean enabled = isEnhanced4gLteModeSettingEnabledByUser();
        boolean isProvisioned = isVolteProvisionedOnDevice();
        boolean voLteFeatureOn = available && enabled && isNonTty && isProvisioned;
        boolean voNrAvailable = isImsOverNrEnabledByPlatform();

        log("updateVoiceCellFeatureValue: available = " + available
                + ", enabled = " + enabled
                + ", nonTTY = " + isNonTty
                + ", provisioned = " + isProvisioned
                + ", voLteFeatureOn = " + voLteFeatureOn
                + ", voNrAvailable = " + voNrAvailable);

        if (voLteFeatureOn) {
            request.addCapabilitiesToEnableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
                    ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
        } else {
            request.addCapabilitiesToDisableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
                    ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
        }
        if (voLteFeatureOn && voNrAvailable) {
            request.addCapabilitiesToEnableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
                    ImsRegistrationImplBase.REGISTRATION_TECH_NR);
        } else {
            request.addCapabilitiesToDisableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
                    ImsRegistrationImplBase.REGISTRATION_TECH_NR);
        }
    }

    /**
     * Update video call configuration
     */
    private void updateVideoCallFeatureValue(CapabilityChangeRequest request, boolean isNonTty) {
        boolean available = isVtEnabledByPlatform();
        boolean vtEnabled = isVtEnabledByUser();
        boolean advancedEnabled = isEnhanced4gLteModeSettingEnabledByUser();
        boolean isDataEnabled = isDataEnabled();
        boolean ignoreDataEnabledChanged = getBooleanCarrierConfig(
                CarrierConfigManager.KEY_IGNORE_DATA_ENABLED_CHANGED_FOR_VIDEO_CALLS);
        boolean isProvisioned = isVtProvisionedOnDevice();
        // TODO: Support carrier config setting about if VT settings should be associated with
        //  advanced calling settings.
        boolean isLteFeatureOn = available && vtEnabled && isNonTty && isProvisioned
                && advancedEnabled && (ignoreDataEnabledChanged || isDataEnabled);
        boolean nrAvailable = isImsOverNrEnabledByPlatform();

        log("updateVideoCallFeatureValue: available = " + available
                + ", vtenabled = " + vtEnabled
                + ", advancedCallEnabled = " + advancedEnabled
                + ", nonTTY = " + isNonTty
                + ", data enabled = " + isDataEnabled
                + ", provisioned = " + isProvisioned
                + ", isLteFeatureOn = " + isLteFeatureOn
                + ", nrAvailable = " + nrAvailable);

        if (isLteFeatureOn) {
            request.addCapabilitiesToEnableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VIDEO,
                    ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
            // VT does not differentiate transport today, do not set IWLAN.
        } else {
            request.addCapabilitiesToDisableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VIDEO,
                    ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
            // VT does not differentiate transport today, do not set IWLAN.
        }

        if (isLteFeatureOn && nrAvailable) {
            request.addCapabilitiesToEnableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VIDEO,
                    ImsRegistrationImplBase.REGISTRATION_TECH_NR);
        } else {
            request.addCapabilitiesToDisableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VIDEO,
                    ImsRegistrationImplBase.REGISTRATION_TECH_NR);
        }
    }

    /**
     * Update WFC config
     */
    private void updateVoiceWifiFeatureAndProvisionedValues(CapabilityChangeRequest request,
     boolean isNonTty) {
        TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
        boolean isNetworkRoaming =  false;
        if (tm == null) {
            loge("updateVoiceWifiFeatureAndProvisionedValues: TelephonyManager is null, assuming"
                    + " not roaming.");
        } else {
            tm = tm.createForSubscriptionId(getSubId());
            isNetworkRoaming = tm.isNetworkRoaming();
        }

        boolean available = isWfcEnabledByPlatform();
        boolean enabled = isWfcEnabledByUser();
        boolean isProvisioned = isWfcProvisionedOnDevice();
        int mode = getWfcMode(isNetworkRoaming);
        boolean roaming = isWfcRoamingEnabledByUser();
        boolean isFeatureOn = available && enabled && isProvisioned;

        log("updateWfcFeatureAndProvisionedValues: available = " + available
                + ", enabled = " + enabled
                + ", mode = " + mode
                + ", provisioned = " + isProvisioned
                + ", roaming = " + roaming
                + ", isFeatureOn = " + isFeatureOn
                + ", isNonTtyWifi = " + isNonTty);

        if (isFeatureOn && isNonTty) {
            request.addCapabilitiesToEnableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
                    ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN);
        } else {
            request.addCapabilitiesToDisableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
                    ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN);
        }

        if (!isFeatureOn) {
            mode = ImsMmTelManager.WIFI_MODE_CELLULAR_PREFERRED;
            roaming = false;
        }
        setWfcModeInternal(mode);
        setWfcRoamingSettingInternal(roaming);
    }

    /**
     * Update Cross SIM config
     */
    private void updateCrossSimFeatureAndProvisionedValues(CapabilityChangeRequest request) {
        if (isCrossSimCallingEnabled()) {
            request.addCapabilitiesToEnableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
                    ImsRegistrationImplBase.REGISTRATION_TECH_CROSS_SIM);
        } else {
            request.addCapabilitiesToDisableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
                    ImsRegistrationImplBase.REGISTRATION_TECH_CROSS_SIM);
        }
    }


    private void updateUtFeatureValue(CapabilityChangeRequest request) {
        boolean isCarrierSupported = isSuppServicesOverUtEnabledByPlatform();

        // check new carrier config first KEY_MMTEL_REQUIRES_PROVISIONING_BUNDLE
        // if that returns false, check deprecated carrier config
        // KEY_CARRIER_UT_PROVISIONING_REQUIRED_BOOL
        boolean requiresProvisioning = isMmTelProvisioningRequired(CAPABILITY_TYPE_UT,
                REGISTRATION_TECH_LTE) || getBooleanCarrierConfig(
                        CarrierConfigManager.KEY_CARRIER_UT_PROVISIONING_REQUIRED_BOOL);
        // Count as "provisioned" if we do not require provisioning.
        boolean isProvisioned = true;
        if (requiresProvisioning) {
            ITelephony telephony = getITelephony();
            // Only track UT over LTE, since we do not differentiate between UT over LTE and IWLAN
            // currently.
            try {
                if (telephony != null) {
                    isProvisioned = telephony.getImsProvisioningStatusForCapability(getSubId(),
                            MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_UT,
                            ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
                }
            } catch (RemoteException e) {
                loge("updateUtFeatureValue: couldn't reach telephony! returning provisioned");
            }
        }
        boolean isFeatureOn = isCarrierSupported && isProvisioned;

        log("updateUtFeatureValue: available = " + isCarrierSupported
                + ", isProvisioned = " + isProvisioned
                + ", enabled = " + isFeatureOn);

        if (isFeatureOn) {
            request.addCapabilitiesToEnableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_UT,
                    ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
        } else {
            request.addCapabilitiesToDisableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_UT,
                    ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
        }
    }

    /**
     * Update call composer capability
     */
    private void updateCallComposerFeatureValue(CapabilityChangeRequest request) {
        boolean isUserSetEnabled = isCallComposerEnabledByUser();
        boolean isCarrierConfigEnabled = getBooleanCarrierConfig(
                CarrierConfigManager.KEY_SUPPORTS_CALL_COMPOSER_BOOL);

        boolean isFeatureOn = isUserSetEnabled && isCarrierConfigEnabled;
        boolean nrAvailable = isImsOverNrEnabledByPlatform();

        log("updateCallComposerFeatureValue: isUserSetEnabled = " + isUserSetEnabled
                + ", isCarrierConfigEnabled = " + isCarrierConfigEnabled
                + ", isFeatureOn = " + isFeatureOn
                + ", nrAvailable = " + nrAvailable);

        if (isFeatureOn) {
            request.addCapabilitiesToEnableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_CALL_COMPOSER,
                            ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
        } else {
            request.addCapabilitiesToDisableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_CALL_COMPOSER,
                            ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
        }
        if (isFeatureOn && nrAvailable) {
            request.addCapabilitiesToEnableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_CALL_COMPOSER,
                    ImsRegistrationImplBase.REGISTRATION_TECH_NR);
        } else {
            request.addCapabilitiesToDisableForTech(
                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_CALL_COMPOSER,
                    ImsRegistrationImplBase.REGISTRATION_TECH_NR);
        }
    }

    /**
     * Do NOT use this directly, instead use {@link #getInstance(Context, int)}.
     */
    private ImsManager(Context context, int phoneId) {
        mContext = context;
        mPhoneId = phoneId;
        mSubscriptionManagerProxy = new DefaultSubscriptionManagerProxy(context);
        mSettingsProxy = new DefaultSettingsProxy();
        mConfigManager = (CarrierConfigManager) context.getSystemService(
                Context.CARRIER_CONFIG_SERVICE);
        mExecutor = new LazyExecutor();
        mBinderCache = new BinderCacheManager<>(ImsManager::getITelephonyInterface);
        // Start off with an empty MmTelFeatureConnection, which will be replaced one an
        // ImsService is available (ImsManager expects a non-null FeatureConnection)
        associate(null /*container*/, SubscriptionManager.INVALID_SUBSCRIPTION_ID);
    }

    /**
     * Used for testing only to inject dependencies.
     */
    @VisibleForTesting
    public ImsManager(Context context, int phoneId, MmTelFeatureConnectionFactory factory,
            SubscriptionManagerProxy subManagerProxy, SettingsProxy settingsProxy,
            BinderCacheManager binderCacheManager) {
        mContext = context;
        mPhoneId = phoneId;
        mMmTelFeatureConnectionFactory = factory;
        mSubscriptionManagerProxy = subManagerProxy;
        mSettingsProxy = settingsProxy;
        mConfigManager = (CarrierConfigManager) context.getSystemService(
                Context.CARRIER_CONFIG_SERVICE);
        // Do not multithread tests
        mExecutor = Runnable::run;
        mBinderCache = binderCacheManager;
        // MmTelFeatureConnection should be replaced for tests with mMmTelFeatureConnectionFactory.
        associate(null /*container*/, SubscriptionManager.INVALID_SUBSCRIPTION_ID);
    }

    /*
     * Returns a flag indicating whether the IMS service is available.
     */
    public boolean isServiceAvailable() {
        return mMmTelConnectionRef.get().isBinderAlive();
    }

    /*
     * Returns a flag indicating whether the IMS service is ready to send requests to lower layers.
     */
    public boolean isServiceReady() {
        return mMmTelConnectionRef.get().isBinderReady();
    }

    /**
     * Opens the IMS service for making calls and/or receiving generic IMS calls as well as
     * register listeners for ECBM, Multiendpoint, and UT if the ImsService supports it.
     * <p>
     * The caller may make subsequent calls through {@link #makeCall}.
     * The IMS service will register the device to the operator's network with the credentials
     * (from ISIM) periodically in order to receive calls from the operator's network.
     * When the IMS service receives a new call, it will call
     * {@link MmTelFeature.Listener#onIncomingCall}
     * @param listener A {@link MmTelFeature.Listener}, which is the interface the
     * {@link MmTelFeature} uses to notify the framework of updates.
     * @param ecbmListener Listener used for ECBM indications.
     * @param multiEndpointListener Listener used for multiEndpoint indications.
     * @throws NullPointerException if {@code listener} is null
     * @throws ImsException if calling the IMS service results in an error
     */
    public void open(MmTelFeature.Listener listener, ImsEcbmStateListener ecbmListener,
            ImsExternalCallStateListener multiEndpointListener) throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();

        if (listener == null) {
            throw new NullPointerException("listener can't be null");
        }

        try {
            c.openConnection(listener, ecbmListener, multiEndpointListener);
        } catch (RemoteException e) {
            throw new ImsException("open()", e, ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Adds registration listener to the IMS service.
     *
     * @param serviceClass a service class specified in {@link ImsServiceClass}
     *      For VoLTE service, it MUST be a {@link ImsServiceClass#MMTEL}.
     * @param listener To listen to IMS registration events; It cannot be null
     * @throws NullPointerException if {@code listener} is null
     * @throws ImsException if calling the IMS service results in an error
     *
     * @deprecated Use {@link #addRegistrationListener(ImsConnectionStateListener)} instead.
     */
    public void addRegistrationListener(int serviceClass, ImsConnectionStateListener listener)
            throws ImsException {
        addRegistrationListener(listener);
    }

    /**
     * Adds registration listener to the IMS service.
     *
     * @param listener To listen to IMS registration events; It cannot be null
     * @throws NullPointerException if {@code listener} is null
     * @throws ImsException if calling the IMS service results in an error
     * @deprecated use {@link #addRegistrationCallback(RegistrationManager.RegistrationCallback,
     * Executor)} instead.
     */
    public void addRegistrationListener(ImsConnectionStateListener listener) throws ImsException {
        if (listener == null) {
            throw new NullPointerException("listener can't be null");
        }
        addRegistrationCallback(listener, getImsThreadExecutor());
        // connect the ImsConnectionStateListener to the new CapabilityCallback.
        addCapabilitiesCallback(new ImsMmTelManager.CapabilityCallback() {
            @Override
            public void onCapabilitiesStatusChanged(
                    MmTelFeature.MmTelCapabilities capabilities) {
                listener.onFeatureCapabilityChangedAdapter(getRegistrationTech(), capabilities);
            }
        }, getImsThreadExecutor());
        log("Registration Callback registered.");
    }

    /**
     * Adds a callback that gets called when IMS registration has changed for the slot ID
     * associated with this ImsManager.
     * @param callback A {@link RegistrationManager.RegistrationCallback} that will notify the
     *                 caller when IMS registration status has changed.
     * @param executor The Executor that the callback should be called on.
     * @throws ImsException when the ImsService connection is not available.
     */
    public void addRegistrationCallback(RegistrationManager.RegistrationCallback callback,
            Executor executor)
            throws ImsException {
        if (callback == null) {
            throw new NullPointerException("registration callback can't be null");
        }

        try {
            callback.setExecutor(executor);
            mMmTelConnectionRef.get().addRegistrationCallback(callback.getBinder());
            log("Registration Callback registered.");
            // Only record if there isn't a RemoteException.
        } catch (IllegalStateException e) {
            throw new ImsException("addRegistrationCallback(IRIB)", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Removes a previously added registration callback that was added via
     * {@link #addRegistrationCallback(RegistrationManager.RegistrationCallback, Executor)} .
     * @param callback A {@link RegistrationManager.RegistrationCallback} that was previously added.
     */
    public void removeRegistrationListener(RegistrationManager.RegistrationCallback callback) {
        if (callback == null) {
            throw new NullPointerException("registration callback can't be null");
        }
        mMmTelConnectionRef.get().removeRegistrationCallback(callback.getBinder());
        log("Registration callback removed.");
    }

    /**
     * Adds a callback that gets called when IMS registration has changed for a specific
     * subscription.
     *
     * @param callback A {@link RegistrationManager.RegistrationCallback} that will notify the
     *                 caller when IMS registration status has changed.
     * @param subId The subscription ID to register this registration callback for.
     * @throws RemoteException when the ImsService connection is not available.
     */
    public void addRegistrationCallbackForSubscription(IImsRegistrationCallback callback, int subId)
            throws RemoteException {
        if (callback == null) {
            throw new IllegalArgumentException("registration callback can't be null");
        }
        mMmTelConnectionRef.get().addRegistrationCallbackForSubscription(callback, subId);
        log("Registration Callback registered.");
        // Only record if there isn't a RemoteException.
    }

    /**
     * Removes a previously registered {@link RegistrationManager.RegistrationCallback} callback
     * that is associated with a specific subscription.
     */
    public void removeRegistrationCallbackForSubscription(IImsRegistrationCallback callback,
            int subId) {
        if (callback == null) {
            throw new IllegalArgumentException("registration callback can't be null");
        }
        mMmTelConnectionRef.get().removeRegistrationCallbackForSubscription(callback, subId);
    }

    /**
     * Adds a callback that gets called when MMTel capability status has changed, for example when
     * Voice over IMS or VT over IMS is not available currently.
     * @param callback A {@link ImsMmTelManager.CapabilityCallback} that will notify the caller when
     *                 MMTel capability status has changed.
     * @param executor The Executor that the callback should be called on.
     * @throws ImsException when the ImsService connection is not available.
     */
    public void addCapabilitiesCallback(ImsMmTelManager.CapabilityCallback callback,
            Executor executor) throws ImsException {
        if (callback == null) {
            throw new NullPointerException("capabilities callback can't be null");
        }

        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        try {
            callback.setExecutor(executor);
            c.addCapabilityCallback(callback.getBinder());
            log("Capability Callback registered.");
            // Only record if there isn't a RemoteException.
        } catch (IllegalStateException e) {
            throw new ImsException("addCapabilitiesCallback(IF)", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Removes a previously registered {@link ImsMmTelManager.CapabilityCallback} callback.
     */
    public void removeCapabilitiesCallback(ImsMmTelManager.CapabilityCallback callback) {
        if (callback == null) {
            throw new NullPointerException("capabilities callback can't be null");
        }

        try {
            MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
            c.removeCapabilityCallback(callback.getBinder());
        } catch (ImsException e) {
            log("Exception removing Capability , exception=" + e);
        }
    }

    /**
     * Adds a callback that gets called when IMS capabilities have changed for a specified
     * subscription.
     * @param callback A {@link ImsMmTelManager.CapabilityCallback} that will notify the caller
     *                 when the IMS Capabilities have changed.
     * @param subId The subscription that is associated with the callback.
     * @throws RemoteException when the ImsService connection is not available.
     */
    public void addCapabilitiesCallbackForSubscription(IImsCapabilityCallback callback, int subId)
            throws RemoteException {
        if (callback == null) {
            throw new IllegalArgumentException("registration callback can't be null");
        }
        mMmTelConnectionRef.get().addCapabilityCallbackForSubscription(callback, subId);
        log("Capability Callback registered for subscription.");
    }

    /**
     * Removes a previously registered {@link ImsMmTelManager.CapabilityCallback} that was
     * associated with a specific subscription.
     */
    public void removeCapabilitiesCallbackForSubscription(IImsCapabilityCallback callback,
            int subId) {
        if (callback == null) {
            throw new IllegalArgumentException("capabilities callback can't be null");
        }
        mMmTelConnectionRef.get().removeCapabilityCallbackForSubscription(callback, subId);
    }

    /**
     * Removes the registration listener from the IMS service.
     *
     * @param listener Previously registered listener that will be removed. Can not be null.
     * @throws NullPointerException if {@code listener} is null
     * @throws ImsException if calling the IMS service results in an error
     * instead.
     */
    public void removeRegistrationListener(ImsConnectionStateListener listener)
            throws ImsException {
        if (listener == null) {
            throw new NullPointerException("listener can't be null");
        }

        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        c.removeRegistrationCallback(listener.getBinder());
        log("Registration Callback/Listener registered.");
        // Only record if there isn't a RemoteException.
    }

    /**
     * Adds a callback that gets called when Provisioning has changed for a specified subscription.
     * @param callback A {@link ProvisioningManager.Callback} that will notify the caller when
     *                 provisioning has changed.
     * @param subId The subscription that is associated with the callback.
     * @throws IllegalStateException when the {@link ImsService} connection is not available.
     * @throws IllegalArgumentException when the {@link IImsConfigCallback} argument is null.
     */
    public void addProvisioningCallbackForSubscription(IImsConfigCallback callback, int subId) {
        if (callback == null) {
            throw new IllegalArgumentException("provisioning callback can't be null");
        }

        mMmTelConnectionRef.get().addProvisioningCallbackForSubscription(callback, subId);
        log("Capability Callback registered for subscription.");
    }

    /**
     * Removes a previously registered {@link ProvisioningManager.Callback} that was associated with
     * a specific subscription.
     * @throws IllegalStateException when the {@link ImsService} connection is not available.
     * @throws IllegalArgumentException when the {@link IImsConfigCallback} argument is null.
     */
    public void removeProvisioningCallbackForSubscription(IImsConfigCallback callback, int subId) {
        if (callback == null) {
            throw new IllegalArgumentException("provisioning callback can't be null");
        }

        mMmTelConnectionRef.get().removeProvisioningCallbackForSubscription(callback, subId);
    }

    public @ImsRegistrationImplBase.ImsRegistrationTech int getRegistrationTech() {
        try {
            return mMmTelConnectionRef.get().getRegistrationTech();
        } catch (RemoteException e) {
            logw("getRegistrationTech: no connection to ImsService.");
            return ImsRegistrationImplBase.REGISTRATION_TECH_NONE;
        }
    }

    public void getRegistrationTech(Consumer<Integer> callback) {
        getImsThreadExecutor().execute(() -> {
            try {
                int tech = mMmTelConnectionRef.get().getRegistrationTech();
                callback.accept(tech);
            } catch (RemoteException e) {
                logw("getRegistrationTech(C): no connection to ImsService.");
                callback.accept(ImsRegistrationImplBase.REGISTRATION_TECH_NONE);
            }
        });
    }

    /**
     * Closes the connection opened in {@link #open} and removes the associated listeners.
     */
    public void close() {
        mMmTelConnectionRef.get().closeConnection();
    }

    /**
     * Create or get the existing configuration interface to provision / withdraw the supplementary
     * service settings.
     * <p>
     * There can only be one connection to the UT interface, so this may only be called by one
     * ImsManager instance. Otherwise, an IllegalStateException will be thrown.
     *
     * @return the Ut interface instance
     * @throws ImsException if getting the Ut interface results in an error
     */
    public ImsUtInterface createOrGetSupplementaryServiceConfiguration() throws ImsException {
        ImsUt iUt;
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        try {
            iUt = c.createOrGetUtInterface();
            if (iUt == null) {
                throw new ImsException("getSupplementaryServiceConfiguration()",
                        ImsReasonInfo.CODE_UT_NOT_SUPPORTED);
            }
        } catch (RemoteException e) {
            throw new ImsException("getSupplementaryServiceConfiguration()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
        return iUt;
    }

    /**
     * Creates a {@link ImsCallProfile} from the service capabilities & IMS registration state.
     *
     * @param serviceType a service type that is specified in {@link ImsCallProfile}
     *        {@link ImsCallProfile#SERVICE_TYPE_NONE}
     *        {@link ImsCallProfile#SERVICE_TYPE_NORMAL}
     *        {@link ImsCallProfile#SERVICE_TYPE_EMERGENCY}
     * @param callType a call type that is specified in {@link ImsCallProfile}
     *        {@link ImsCallProfile#CALL_TYPE_VOICE}
     *        {@link ImsCallProfile#CALL_TYPE_VT}
     *        {@link ImsCallProfile#CALL_TYPE_VT_TX}
     *        {@link ImsCallProfile#CALL_TYPE_VT_RX}
     *        {@link ImsCallProfile#CALL_TYPE_VT_NODIR}
     *        {@link ImsCallProfile#CALL_TYPE_VS}
     *        {@link ImsCallProfile#CALL_TYPE_VS_TX}
     *        {@link ImsCallProfile#CALL_TYPE_VS_RX}
     * @return a {@link ImsCallProfile} object
     * @throws ImsException if calling the IMS service results in an error
     */
    public ImsCallProfile createCallProfile(int serviceType, int callType) throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();

        try {
            return c.createCallProfile(serviceType, callType);
        } catch (RemoteException e) {
            throw new ImsException("createCallProfile()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Informs the {@link ImsService} of the {@link RtpHeaderExtensionType}s which the framework
     * intends to use for incoming and outgoing calls.
     * <p>
     * See {@link RtpHeaderExtensionType} for more information.
     * @param types The RTP header extension types to use for incoming and outgoing calls, or
     *              empty list if none defined.
     * @throws ImsException
     */
    public void setOfferedRtpHeaderExtensionTypes(@NonNull Set<RtpHeaderExtensionType> types)
            throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();

        try {
            c.changeOfferedRtpHeaderExtensionTypes(types);
        } catch (RemoteException e) {
            throw new ImsException("setOfferedRtpHeaderExtensionTypes()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Creates a {@link ImsCall} to make a call.
     *
     * @param profile a call profile to make the call
     *      (it contains service type, call type, media information, etc.)
     * @param callees participants to invite the conference call
     * @param listener listen to the call events from {@link ImsCall}
     * @return a {@link ImsCall} object
     * @throws ImsException if calling the IMS service results in an error
     */
    public ImsCall makeCall(ImsCallProfile profile, String[] callees,
            ImsCall.Listener listener) throws ImsException {
        if (DBG) {
            log("makeCall :: profile=" + profile);
        }

        // Check we are still alive
        getOrThrowExceptionIfServiceUnavailable();

        ImsCall call = new ImsCall(mContext, profile);

        call.setListener(listener);
        ImsCallSession session = createCallSession(profile);

        if ((callees != null) && (callees.length == 1) && !(session.isMultiparty())) {
            call.start(session, callees[0]);
        } else {
            call.start(session, callees);
        }

        return call;
    }

    /**
     * Creates a {@link ImsCall} to take an incoming call.
     *
     * @param listener to listen to the call events from {@link ImsCall}
     * @return a {@link ImsCall} object
     * @throws ImsException if calling the IMS service results in an error
     */
    public ImsCall takeCall(IImsCallSession session, ImsCall.Listener listener)
            throws ImsException {
        // Check we are still alive
        getOrThrowExceptionIfServiceUnavailable();
        try {
            if (session == null) {
                throw new ImsException("No pending session for the call",
                        ImsReasonInfo.CODE_LOCAL_NO_PENDING_CALL);
            }

            ImsCall call = new ImsCall(mContext, session.getCallProfile());

            call.attachSession(new ImsCallSession(session));
            call.setListener(listener);

            return call;
        } catch (Throwable t) {
            loge("takeCall caught: ", t);
            throw new ImsException("takeCall()", t, ImsReasonInfo.CODE_UNSPECIFIED);
        }
    }

    /**
     * Gets the config interface to get/set service/capability parameters.
     *
     * @return the ImsConfig instance.
     * @throws ImsException if getting the setting interface results in an error.
     */
    @UnsupportedAppUsage
    public ImsConfig getConfigInterface() throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();

        IImsConfig config = c.getConfig();
        if (config == null) {
            throw new ImsException("getConfigInterface()",
                    ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE);
        }
        return new ImsConfig(config);
    }

    /**
     * Enable or disable a capability for multiple radio technologies.
     */
    public void changeMmTelCapability(boolean isEnabled, int capability,
            int... radioTechs) throws ImsException {
        CapabilityChangeRequest request = new CapabilityChangeRequest();
        if (isEnabled) {
            for (int tech : radioTechs) {
                request.addCapabilitiesToEnableForTech(capability, tech);
            }
        } else {
            for (int tech : radioTechs) {
                request.addCapabilitiesToDisableForTech(capability, tech);
            }
        }
        changeMmTelCapability(request);
    }

    private void changeMmTelCapability(CapabilityChangeRequest r) throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        try {
            logi("changeMmTelCapability: changing capabilities for sub: " + getSubId()
                    + ", request: " + r);
            c.changeEnabledCapabilities(r, null);
            ImsStatsCallback cb = getStatsCallback(mPhoneId);
            if (cb == null) {
                return;
            }
            for (CapabilityChangeRequest.CapabilityPair enabledCaps : r.getCapabilitiesToEnable()) {
                cb.onEnabledMmTelCapabilitiesChanged(enabledCaps.getCapability(),
                        enabledCaps.getRadioTech(), true);
            }
            for (CapabilityChangeRequest.CapabilityPair disabledCaps :
                    r.getCapabilitiesToDisable()) {
                cb.onEnabledMmTelCapabilitiesChanged(disabledCaps.getCapability(),
                        disabledCaps.getRadioTech(), false);
            }
        } catch (RemoteException e) {
            throw new ImsException("changeMmTelCapability(CCR)", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    private boolean updateRttConfigValue() {
        // If there's no active sub anywhere on the device, enable RTT on the modem so that
        // the device can make an emergency call.

        boolean isActiveSubscriptionPresent = isActiveSubscriptionPresent();
        boolean isCarrierSupported =
                getBooleanCarrierConfig(CarrierConfigManager.KEY_RTT_SUPPORTED_BOOL)
                || !isActiveSubscriptionPresent;

        int defaultRttMode =
                getIntCarrierConfig(CarrierConfigManager.KEY_DEFAULT_RTT_MODE_INT);
        int rttMode = mSettingsProxy.getSecureIntSetting(mContext.getContentResolver(),
                Settings.Secure.RTT_CALLING_MODE, defaultRttMode);
        logi("defaultRttMode = " + defaultRttMode + " rttMode = " + rttMode);
        boolean isRttAlwaysOnCarrierConfig = getBooleanCarrierConfig(
                CarrierConfigManager.KEY_IGNORE_RTT_MODE_SETTING_BOOL);
        if (isRttAlwaysOnCarrierConfig && rttMode == defaultRttMode) {
            mSettingsProxy.putSecureIntSetting(mContext.getContentResolver(),
                    Settings.Secure.RTT_CALLING_MODE, defaultRttMode);
        }

        boolean isRttUiSettingEnabled = mSettingsProxy.getSecureIntSetting(
                mContext.getContentResolver(), Settings.Secure.RTT_CALLING_MODE, 0) != 0;

        boolean shouldImsRttBeOn = isRttUiSettingEnabled || isRttAlwaysOnCarrierConfig;
        logi("update RTT: settings value: " + isRttUiSettingEnabled + " always-on carrierconfig: "
                + isRttAlwaysOnCarrierConfig
                + "isActiveSubscriptionPresent: " + isActiveSubscriptionPresent);

        if (isCarrierSupported) {
            setRttConfig(shouldImsRttBeOn);
        } else {
            setRttConfig(false);
        }
        return isCarrierSupported && shouldImsRttBeOn;
    }

    private void setRttConfig(boolean enabled) {
        final int value = enabled ? ProvisioningManager.PROVISIONING_VALUE_ENABLED :
                ProvisioningManager.PROVISIONING_VALUE_DISABLED;
        getImsThreadExecutor().execute(() -> {
            try {
                logi("Setting RTT enabled to " + enabled);
                getConfigInterface().setProvisionedValue(
                        ImsConfig.ConfigConstants.RTT_SETTING_ENABLED, value);
            } catch (ImsException e) {
                loge("Unable to set RTT value enabled to " + enabled + ": " + e);
            }
        });
    }

    public boolean queryMmTelCapability(
            @MmTelFeature.MmTelCapabilities.MmTelCapability int capability,
            @ImsRegistrationImplBase.ImsRegistrationTech int radioTech) throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();

        BlockingQueue<Boolean> result = new LinkedBlockingDeque<>(1);

        try {
            c.queryEnabledCapabilities(capability, radioTech, new IImsCapabilityCallback.Stub() {
                        @Override
                        public void onQueryCapabilityConfiguration(int resCap, int resTech,
                                boolean enabled) {
                            if (resCap == capability && resTech == radioTech) {
                                result.offer(enabled);
                            }
                        }

                        @Override
                        public void onChangeCapabilityConfigurationError(int capability,
                                int radioTech, int reason) {

                        }

                        @Override
                        public void onCapabilitiesStatusChanged(int config) {

                        }
                    });
        } catch (RemoteException e) {
            throw new ImsException("queryMmTelCapability()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }

        try {
            return result.poll(RESPONSE_WAIT_TIME_MS, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            logw("queryMmTelCapability: interrupted while waiting for response");
        }
        return false;
    }

    public boolean queryMmTelCapabilityStatus(
            @MmTelFeature.MmTelCapabilities.MmTelCapability int capability,
            @ImsRegistrationImplBase.ImsRegistrationTech int radioTech) throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();

        if (getRegistrationTech() != radioTech)
            return false;

        try {

            MmTelFeature.MmTelCapabilities capabilities =
                    c.queryCapabilityStatus();

            return capabilities.isCapable(capability);
        } catch (RemoteException e) {
            throw new ImsException("queryMmTelCapabilityStatus()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Enable the RTT configuration on this device.
     */
    public void setRttEnabled(boolean enabled) {
        if (enabled) {
            // Override this setting if RTT is enabled.
            setEnhanced4gLteModeSetting(true /*enabled*/);
        }
        setRttConfig(enabled);
    }

    /**
     * Set the TTY mode. This is the actual tty mode (varies depending on peripheral status)
     */
    public void setTtyMode(int ttyMode) throws ImsException {
        boolean isNonTtyOrTtyOnVolteEnabled = isTtyOnVoLteCapable() ||
                (ttyMode == TelecomManager.TTY_MODE_OFF);

        boolean isNonTtyOrTtyOnWifiEnabled = isTtyOnVoWifiCapable() ||
                (ttyMode == TelecomManager.TTY_MODE_OFF);

        CapabilityChangeRequest request = new CapabilityChangeRequest();
        updateVoiceCellFeatureValue(request, isNonTtyOrTtyOnVolteEnabled);
        updateVideoCallFeatureValue(request, isNonTtyOrTtyOnVolteEnabled);
        updateVoiceWifiFeatureAndProvisionedValues(request, isNonTtyOrTtyOnWifiEnabled);
        // update MMTEL caps for the new configuration.
        changeMmTelCapability(request);
        if (isImsNeeded(request)) {
            // Only turn on IMS if voice/video is enabled now in the new configuration.
            turnOnIms();
        }
    }

    /**
     * Sets the UI TTY mode. This is the preferred TTY mode that the user sets in the call
     * settings screen.
     * @param uiTtyMode TTY Mode, valid options are:
     *         - {@link com.android.internal.telephony.Phone#TTY_MODE_OFF}
     *         - {@link com.android.internal.telephony.Phone#TTY_MODE_FULL}
     *         - {@link com.android.internal.telephony.Phone#TTY_MODE_HCO}
     *         - {@link com.android.internal.telephony.Phone#TTY_MODE_VCO}
     * @param onComplete A Message that will be called by the ImsService when it has completed this
     *           operation or null if not waiting for an async response. The Message must contain a
     *           valid {@link Message#replyTo} {@link android.os.Messenger}, since it will be passed
     *           through Binder to another process.
     */
    public void setUiTTYMode(Context context, int uiTtyMode, Message onComplete)
            throws ImsException {

        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        try {
            c.setUiTTYMode(uiTtyMode, onComplete);
        } catch (RemoteException e) {
            throw new ImsException("setTTYMode()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Notifies the change of user setting.
     *
     * @param enabled indicates whether the user setting for call waiting is enabled or not.
     */
    public void setTerminalBasedCallWaitingStatus(boolean enabled) throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        try {
            c.setTerminalBasedCallWaitingStatus(enabled);
        } catch (ServiceSpecificException se) {
            if (se.errorCode
                    == android.telephony.ims.ImsException.CODE_ERROR_UNSUPPORTED_OPERATION) {
                throw new ImsException("setTerminalBasedCallWaitingStatus()", se,
                        ImsReasonInfo.CODE_LOCAL_IMS_NOT_SUPPORTED_ON_DEVICE);
            } else {
                throw new ImsException("setTerminalBasedCallWaitingStatus()", se,
                        ImsReasonInfo.CODE_LOCAL_INTERNAL_ERROR);
            }
        } catch (RemoteException e) {
            throw new ImsException("setTerminalBasedCallWaitingStatus()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Returns whether all of the capabilities specified are capable or not.
     */
    public boolean isCapable(@ImsService.ImsServiceCapability long capabilities)
            throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        try {
            return c.isCapable(capabilities);
        } catch (RemoteException e) {
            throw new ImsException("isCapable()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Notifies SRVCC started.
     * @param cb The callback to receive the list of {@link SrvccCall}.
     */
    public void notifySrvccStarted(ISrvccStartedCallback cb)
            throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        try {
            c.notifySrvccStarted(cb);
        } catch (RemoteException e) {
            throw new ImsException("notifySrvccStarted", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Notifies SRVCC is completed, IMS service will hang up all calls.
     */
    public void notifySrvccCompleted() throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        try {
            c.notifySrvccCompleted();
        } catch (RemoteException e) {
            throw new ImsException("notifySrvccCompleted", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Notifies SRVCC failed. IMS service will recover and continue calls over IMS.
     */
    public void notifySrvccFailed() throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        try {
            c.notifySrvccFailed();
        } catch (RemoteException e) {
            throw new ImsException("notifySrvccFailed", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Notifies SRVCC is canceled. IMS service will recover and continue calls over IMS.
     */
    public void notifySrvccCanceled() throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        try {
            c.notifySrvccCanceled();
        } catch (RemoteException e) {
            throw new ImsException("notifySrvccCanceled", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Notifies that radio triggered IMS deregistration.
     * @param reason the reason why the deregistration is triggered.
     */
    public void triggerDeregistration(@ImsRegistrationImplBase.ImsDeregistrationReason int reason)
            throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        try {
            c.triggerDeregistration(reason);
        } catch (RemoteException e) {
            throw new ImsException("triggerDeregistration", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    public int getImsServiceState() throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        return c.getFeatureState();
    }

    public void setMediaThreshold(@MediaQualityStatus.MediaSessionType int sessionType,
            MediaThreshold threshold) throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        try {
            c.setMediaThreshold(sessionType, threshold);
        } catch (RemoteException e) {
            loge("setMediaThreshold Failed.");
        }
    }

    public MediaQualityStatus queryMediaQualityStatus (
            @MediaQualityStatus.MediaSessionType int sessionType) throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        try {
            return c.queryMediaQualityStatus(sessionType);
        } catch (RemoteException e) {
            loge("queryMediaQualityStatus Failed.");
            return null;
        }
    }

    @Override
    public void updateFeatureState(int state) {
        mMmTelConnectionRef.get().updateFeatureState(state);
    }

    @Override
    public void updateFeatureCapabilities(long capabilities) {
        mMmTelConnectionRef.get().updateFeatureCapabilities(capabilities);
    }

    public void getImsServiceState(Consumer<Integer> result) {
        getImsThreadExecutor().execute(() -> {
            try {
                result.accept(getImsServiceState());
            } catch (ImsException e) {
                // In the case that the ImsService is not available, report unavailable.
                result.accept(ImsFeature.STATE_UNAVAILABLE);
            }
        });
    }

    /**
     * @return An Executor that should be used to execute potentially long-running operations.
     */
    private Executor getImsThreadExecutor() {
        return mExecutor;
    }

    /**
     * Get the boolean config from carrier config manager.
     *
     * @param key config key defined in CarrierConfigManager
     * @return boolean value of corresponding key.
     */
    private boolean getBooleanCarrierConfig(String key) {
        PersistableBundle b = null;
        if (mConfigManager != null) {
            // If an invalid subId is used, this bundle will contain default values.
            b = mConfigManager.getConfigForSubId(getSubId());
        }
        if (b != null) {
            return b.getBoolean(key);
        } else {
            // Return static default defined in CarrierConfigManager.
            return CarrierConfigManager.getDefaultConfig().getBoolean(key);
        }
    }

    /**
     * Get the int config from carrier config manager.
     *
     * @param key config key defined in CarrierConfigManager
     * @return integer value of corresponding key.
     */
    private int getIntCarrierConfig(String key) {
        PersistableBundle b = null;
        if (mConfigManager != null) {
            // If an invalid subId is used, this bundle will contain default values.
            b = mConfigManager.getConfigForSubId(getSubId());
        }
        if (b != null) {
            return b.getInt(key);
        } else {
            // Return static default defined in CarrierConfigManager.
            return CarrierConfigManager.getDefaultConfig().getInt(key);
        }
    }

    /**
     * Get the int[] config from carrier config manager.
     *
     * @param key config key defined in CarrierConfigManager
     * @return int[] values of the corresponding key.
     */
    private int[] getIntArrayCarrierConfig(String key) {
        PersistableBundle b = null;
        if (mConfigManager != null) {
            // If an invalid subId is used, this bundle will contain default values.
            b = mConfigManager.getConfigForSubId(getSubId());
        }
        if (b != null) {
            return b.getIntArray(key);
        } else {
            // Return static default defined in CarrierConfigManager.
            return CarrierConfigManager.getDefaultConfig().getIntArray(key);
        }
    }

    /**
     * Checks to see if the ImsService Binder is connected. If it is not, we try to create the
     * connection again.
     */
    private MmTelFeatureConnection getOrThrowExceptionIfServiceUnavailable()
            throws ImsException {
        if (!isImsSupportedOnDevice(mContext)) {
            throw new ImsException("IMS not supported on device.",
                    ImsReasonInfo.CODE_LOCAL_IMS_NOT_SUPPORTED_ON_DEVICE);
        }
        MmTelFeatureConnection c = mMmTelConnectionRef.get();
        if (c == null || !c.isBinderAlive()) {
            throw new ImsException("Service is unavailable",
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
        if (getSubId() != c.getSubId()) {
            logi("Trying to get MmTelFeature when it is still setting up, curr subId=" + getSubId()
                    + ", target subId=" + c.getSubId());
            throw new ImsException("Service is still initializing",
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
        return c;
    }

    @Override
    public void registerFeatureCallback(int slotId, IImsServiceFeatureCallback cb) {
        try {
            ITelephony telephony = mBinderCache.listenOnBinder(cb, () -> {
                try {
                    cb.imsFeatureRemoved(
                            FeatureConnector.UNAVAILABLE_REASON_SERVER_UNAVAILABLE);
                } catch (RemoteException ignore) {} // This is local.
            });

            if (telephony != null) {
                telephony.registerMmTelFeatureCallback(slotId, cb);
            } else {
                cb.imsFeatureRemoved(FeatureConnector.UNAVAILABLE_REASON_SERVER_UNAVAILABLE);
            }
        } catch (ServiceSpecificException e) {
            try {
                switch (e.errorCode) {
                    case android.telephony.ims.ImsException.CODE_ERROR_UNSUPPORTED_OPERATION:
                        cb.imsFeatureRemoved(FeatureConnector.UNAVAILABLE_REASON_IMS_UNSUPPORTED);
                        break;
                    default: {
                        cb.imsFeatureRemoved(
                                FeatureConnector.UNAVAILABLE_REASON_SERVER_UNAVAILABLE);
                    }
                }
            } catch (RemoteException ignore) {} // Already dead anyway if this happens.
        } catch (RemoteException e) {
            try {
                cb.imsFeatureRemoved(FeatureConnector.UNAVAILABLE_REASON_SERVER_UNAVAILABLE);
            } catch (RemoteException ignore) {} // Already dead if this happens.
        }
    }

    @Override
    public void unregisterFeatureCallback(IImsServiceFeatureCallback cb) {
        try {
            ITelephony telephony = mBinderCache.removeRunnable(cb);
            if (telephony != null) {
                telephony.unregisterImsFeatureCallback(cb);
            }
        } catch (RemoteException e) {
            // This means that telephony died, so do not worry about it.
            loge("unregisterImsFeatureCallback (MMTEL), RemoteException: " + e.getMessage());
        }
    }

    @Override
    public void associate(ImsFeatureContainer c, int subId) {
        if (c == null) {
            mMmTelConnectionRef.set(mMmTelFeatureConnectionFactory.create(
                    mContext, mPhoneId, subId, null, null, null, null));
        } else {
            mMmTelConnectionRef.set(mMmTelFeatureConnectionFactory.create(
                    mContext, mPhoneId, subId, IImsMmTelFeature.Stub.asInterface(c.imsFeature),
                    c.imsConfig, c.imsRegistration, c.sipTransport));
        }
    }

    @Override
    public void invalidate() {
        mMmTelConnectionRef.get().onRemovedOrDied();
    }

    private ITelephony getITelephony() {
        return mBinderCache.getBinder();
    }

    private static ITelephony getITelephonyInterface() {
        return ITelephony.Stub.asInterface(
                TelephonyFrameworkInitializer
                        .getTelephonyServiceManager()
                        .getTelephonyServiceRegisterer()
                        .get());
    }

    /**
     * Creates a {@link ImsCallSession} with the specified call profile.
     * Use other methods, if applicable, instead of interacting with
     * {@link ImsCallSession} directly.
     *
     * @param profile a call profile to make the call
     */
    private ImsCallSession createCallSession(ImsCallProfile profile) throws ImsException {
        try {
            MmTelFeatureConnection c = mMmTelConnectionRef.get();
            // Throws an exception if the ImsService Feature is not ready to accept commands.
            return new ImsCallSession(c.createCallSession(profile));
        } catch (RemoteException e) {
            logw("CreateCallSession: Error, remote exception: " + e.getMessage());
            throw new ImsException("createCallSession()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);

        }
    }

    private void log(String s) {
        Rlog.d(TAG + mLogTagPostfix + " [" + mPhoneId + "]", s);
    }

    private void logi(String s) {
        Rlog.i(TAG + mLogTagPostfix + " [" + mPhoneId + "]", s);
    }

    private void logw(String s) {
        Rlog.w(TAG + mLogTagPostfix + " [" + mPhoneId + "]", s);
    }

    private void loge(String s) {
        Rlog.e(TAG + mLogTagPostfix + " [" + mPhoneId + "]", s);
    }

    private void loge(String s, Throwable t) {
        Rlog.e(TAG + mLogTagPostfix + " [" + mPhoneId + "]", s, t);
    }

    /**
     * Used for turning on IMS.if its off already
     */
    private void turnOnIms() throws ImsException {
        TelephonyManager tm = (TelephonyManager)
                mContext.getSystemService(Context.TELEPHONY_SERVICE);
        tm.enableIms(mPhoneId);
    }

    private boolean isImsTurnOffAllowed() {
        return isTurnOffImsAllowedByPlatform()
                && (!isWfcEnabledByPlatform()
                || !isWfcEnabledByUser());
    }

    /**
     * Used for turning off IMS completely in order to make the device CSFB'ed.
     * Once turned off, all calls will be over CS.
     */
    private void turnOffIms() throws ImsException {
        TelephonyManager tm = (TelephonyManager)
                mContext.getSystemService(Context.TELEPHONY_SERVICE);
        tm.disableIms(mPhoneId);
    }

    /**
     * Gets the ECBM interface to request ECBM exit.
     * <p>
     * This should only be called after {@link #open} has been called.
     *
     * @return the ECBM interface instance
     * @throws ImsException if getting the ECBM interface results in an error
     */
    public ImsEcbm getEcbmInterface() throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        ImsEcbm iEcbm = c.getEcbmInterface();

        if (iEcbm == null) {
            throw new ImsException("getEcbmInterface()",
                    ImsReasonInfo.CODE_ECBM_NOT_SUPPORTED);
        }
        return iEcbm;
    }

    public void sendSms(int token, int messageRef, String format, String smsc, boolean isRetry,
            byte[] pdu) throws ImsException {
        try {
            mMmTelConnectionRef.get().sendSms(token, messageRef, format, smsc, isRetry, pdu);
        } catch (RemoteException e) {
            throw new ImsException("sendSms()", e, ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    public void onMemoryAvailable(int token) throws ImsException {
        try {
            mMmTelConnectionRef.get().onMemoryAvailable(token);
        } catch (RemoteException e) {
            throw new ImsException("onMemoryAvailable()", e,
                ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    public void acknowledgeSms(int token, int messageRef, int result) throws ImsException {
        try {
            mMmTelConnectionRef.get().acknowledgeSms(token, messageRef, result);
        } catch (RemoteException e) {
            throw new ImsException("acknowledgeSms()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    public void acknowledgeSms(int token, int messageRef, int result, byte[] pdu) throws ImsException {
        try {
            mMmTelConnectionRef.get().acknowledgeSms(token, messageRef, result, pdu);
        } catch (RemoteException e) {
            throw new ImsException("acknowledgeSms()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    public void acknowledgeSmsReport(int token, int messageRef, int result) throws  ImsException{
        try {
            mMmTelConnectionRef.get().acknowledgeSmsReport(token, messageRef, result);
        } catch (RemoteException e) {
            throw new ImsException("acknowledgeSmsReport()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    public String getSmsFormat() throws ImsException{
        try {
            return mMmTelConnectionRef.get().getSmsFormat();
        } catch (RemoteException e) {
            throw new ImsException("getSmsFormat()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    public void setSmsListener(IImsSmsListener listener) throws ImsException {
        try {
            mMmTelConnectionRef.get().setSmsListener(listener);
        } catch (RemoteException e) {
            throw new ImsException("setSmsListener()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    public void onSmsReady() throws ImsException {
        try {
            mMmTelConnectionRef.get().onSmsReady();
        } catch (RemoteException e) {
            throw new ImsException("onSmsReady()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Determines whether or not a call with the specified numbers should be placed over IMS or over
     * CSFB.
     * @param isEmergency is at least one call an emergency number.
     * @param numbers A {@link String} array containing the numbers in the call being placed. Can
     *         be multiple numbers in the case of dialing out a conference.
     * @return The result of the query, one of the following values:
     *         - {@link MmTelFeature#PROCESS_CALL_IMS}
     *         - {@link MmTelFeature#PROCESS_CALL_CSFB}
     * @throws ImsException if the ImsService is not available. In this case, we should fall back
     * to CSFB anyway.
     */
    public @MmTelFeature.ProcessCallResult int shouldProcessCall(boolean isEmergency,
            String[] numbers) throws ImsException {
        try {
            MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
            return c.shouldProcessCall(isEmergency, numbers);
        } catch (RemoteException e) {
            throw new ImsException("shouldProcessCall()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }

    /**
     * Resets ImsManager settings back to factory defaults.
     *
     * @deprecated Doesn't support MSIM devices. Use {@link #factoryReset()} instead.
     *
     * @hide
     */
    public static void factoryReset(Context context) {
        DefaultSubscriptionManagerProxy p = new DefaultSubscriptionManagerProxy(context);
        ImsManager mgr = ImsManager.getInstance(context, p.getDefaultVoicePhoneId());
        if (mgr != null) {
            mgr.factoryReset();
        }
        Rlog.e(TAG, "factoryReset: ImsManager null.");
    }

    /**
     * Resets ImsManager settings back to factory defaults.
     *
     * @hide
     */
    public void factoryReset() {
        int subId = getSubId();
        if (!isSubIdValid(subId)) {
            loge("factoryReset: invalid sub id, can not reset siminfo db settings; subId="
                    + subId);
            return;
        }
        // Set VoLTE to default
        mSubscriptionManagerProxy.setSubscriptionProperty(subId,
                SubscriptionManager.ENHANCED_4G_MODE_ENABLED,
                Integer.toString(SUB_PROPERTY_NOT_INITIALIZED));

        // Set VoWiFi to default
        mSubscriptionManagerProxy.setSubscriptionProperty(subId,
                SubscriptionManager.WFC_IMS_ENABLED,
                Integer.toString(SUB_PROPERTY_NOT_INITIALIZED));

        // Set VoWiFi mode to default
        mSubscriptionManagerProxy.setSubscriptionProperty(subId,
                SubscriptionManager.WFC_IMS_MODE,
                Integer.toString(SUB_PROPERTY_NOT_INITIALIZED));

        // Set VoWiFi roaming to default
        mSubscriptionManagerProxy.setSubscriptionProperty(subId,
                SubscriptionManager.WFC_IMS_ROAMING_ENABLED,
                Integer.toString(SUB_PROPERTY_NOT_INITIALIZED));

        // Set VoWiFi roaming mode to default
        mSubscriptionManagerProxy.setSubscriptionProperty(subId,
                SubscriptionManager.WFC_IMS_ROAMING_MODE,
                Integer.toString(SUB_PROPERTY_NOT_INITIALIZED));


        // Set VT to default
        mSubscriptionManagerProxy.setSubscriptionProperty(subId,
                SubscriptionManager.VT_IMS_ENABLED,
                Integer.toString(SUB_PROPERTY_NOT_INITIALIZED));

        // Set RCS UCE to default
        mSubscriptionManagerProxy.setSubscriptionProperty(subId,
                SubscriptionManager.IMS_RCS_UCE_ENABLED, Integer.toString(
                        SUBINFO_PROPERTY_FALSE));
        // Push settings
        try {
            reevaluateCapabilities();
        } catch (ImsException e) {
            loge("factoryReset, exception: " + e);
        }
    }

    private boolean isDataEnabled() {
        TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
        if (tm == null) {
            loge("isDataEnabled: TelephonyManager not available, returning false...");
            return false;
        }
        tm = tm.createForSubscriptionId(getSubId());
        return tm.isDataConnectionAllowed();
    }

    private boolean isVolteProvisioned() {
        return getImsProvisionedBoolNoException(CAPABILITY_TYPE_VOICE, REGISTRATION_TECH_LTE);
    }

    private boolean isEabProvisioned() {
        return getRcsProvisionedBoolNoException(CAPABILITY_TYPE_PRESENCE_UCE,
                REGISTRATION_TECH_LTE);
    }

    private boolean isWfcProvisioned() {
        return getImsProvisionedBoolNoException(CAPABILITY_TYPE_VOICE, REGISTRATION_TECH_IWLAN);
    }

    private boolean isVtProvisioned() {
        return getImsProvisionedBoolNoException(CAPABILITY_TYPE_VIDEO, REGISTRATION_TECH_LTE);
    }

    private boolean isMmTelProvisioningRequired(int capability, int tech) {
        int subId = getSubId();
        if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
            logw("isMmTelProvisioningRequired subId is invalid");
            return false;
        }

        ITelephony iTelephony = getITelephony();
        if (iTelephony == null) {
            logw("isMmTelProvisioningRequired ITelephony interface is invalid");
            return false;
        }

        boolean required = false;
        try {
            required = iTelephony.isProvisioningRequiredForCapability(subId, capability,
                    tech);
        } catch (RemoteException | IllegalArgumentException e) {
            logw("isMmTelProvisioningRequired : operation failed" + " capability=" + capability
                    + " tech=" + tech + ". Exception:" + e.getMessage());
        }

        log("MmTel Provisioning required " + required + " for capability " + capability);
        return required;
    }

    private boolean isRcsProvisioningRequired(int capability, int tech) {
        int subId = getSubId();
        if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
            logw("isRcsProvisioningRequired subId is invalid");
            return false;
        }

        ITelephony iTelephony = getITelephony();
        if (iTelephony == null) {
            logw("isRcsProvisioningRequired ITelephony interface is invalid");
            return false;
        }

        boolean required = false;
        try {
            required = iTelephony.isRcsProvisioningRequiredForCapability(subId, capability,
                    tech);
        } catch (RemoteException | IllegalArgumentException e) {
            logw("isRcsProvisioningRequired : operation failed" + " capability=" + capability
                    + " tech=" + tech + ". Exception:" + e.getMessage());
        }

        log("Rcs Provisioning required " + required + " for capability " + capability);
        return required;
    }

    private static String booleanToPropertyString(boolean bool) {
        return bool ? "1" : "0";
    }

    public int getConfigInt(int key) throws ImsException {
        if (isLocalImsConfigKey(key)) {
            return getLocalImsConfigKeyInt(key);
        } else {
            return getConfigInterface().getConfigInt(key);
        }
    }

    public String getConfigString(int key) throws ImsException {
        if (isLocalImsConfigKey(key)) {
            return getLocalImsConfigKeyString(key);
        } else {
            return getConfigInterface().getConfigString(key);
        }
    }

    public int setConfig(int key, int value) throws ImsException, RemoteException {
        if (isLocalImsConfigKey(key)) {
            return setLocalImsConfigKeyInt(key, value);
        } else {
            return getConfigInterface().setConfig(key, value);
        }
    }

    public int setConfig(int key, String value) throws ImsException, RemoteException {
        if (isLocalImsConfigKey(key)) {
            return setLocalImsConfigKeyString(key, value);
        } else {
            return getConfigInterface().setConfig(key, value);
        }
    }

    /**
     * Gets the configuration value that supported in frameworks.
     *
     * @param key, as defined in com.android.ims.ProvisioningManager.
     * @return the value in Integer format
     */
    private int getLocalImsConfigKeyInt(int key) {
        int result = ProvisioningManager.PROVISIONING_RESULT_UNKNOWN;

        switch (key) {
            case KEY_VOIMS_OPT_IN_STATUS:
                result = isVoImsOptInEnabled() ? 1 : 0;
                break;
        }
        log("getLocalImsConfigKeInt() for key:" + key + ", result: " + result);
        return result;
    }

    /**
     * Gets the configuration value that supported in frameworks.
     *
     * @param key, as defined in com.android.ims.ProvisioningManager.
     * @return the value in String format
     */
    private String getLocalImsConfigKeyString(int key) {
        String result = "";

        switch (key) {
            case KEY_VOIMS_OPT_IN_STATUS:
                result = booleanToPropertyString(isVoImsOptInEnabled());

                break;
        }
        log("getLocalImsConfigKeyString() for key:" + key + ", result: " + result);
        return result;
    }

    /**
     * Sets the configuration value that supported in frameworks.
     *
     * @param key, as defined in com.android.ims.ProvisioningManager.
     * @param value in Integer format.
     * @return as defined in com.android.ims.ProvisioningManager#OperationStatusConstants
     */
    private int setLocalImsConfigKeyInt(int key, int value) throws ImsException, RemoteException {
        int result = ImsConfig.OperationStatusConstants.UNKNOWN;

        switch (key) {
            case KEY_VOIMS_OPT_IN_STATUS:
                result = setVoImsOptInSetting(value);
                reevaluateCapabilities();
                break;
        }
        log("setLocalImsConfigKeyInt() for" +
                " key: " + key +
                ", value: " + value +
                ", result: " + result);

        // Notify ims config changed
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        IImsConfig config = c.getConfig();
        config.notifyIntImsConfigChanged(key, value);

        return result;
    }

    /**
     * Sets the configuration value that supported in frameworks.
     *
     * @param key, as defined in com.android.ims.ProvisioningManager.
     * @param value in String format.
     * @return as defined in com.android.ims.ProvisioningManager#OperationStatusConstants
     */
    private int setLocalImsConfigKeyString(int key, String value)
            throws ImsException, RemoteException {
        int result = ImsConfig.OperationStatusConstants.UNKNOWN;

        switch (key) {
            case KEY_VOIMS_OPT_IN_STATUS:
                result = setVoImsOptInSetting(Integer.parseInt(value));
                reevaluateCapabilities();
                break;
        }
        log("setLocalImsConfigKeyString() for" +
                " key: " + key +
                ", value: " + value +
                ", result: " + result);

        // Notify ims config changed
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();
        IImsConfig config = c.getConfig();
        config.notifyStringImsConfigChanged(key, value);

        return result;
    }

    /**
     * Check the config whether supported by framework.
     *
     * @param key, as defined in com.android.ims.ProvisioningManager.
     * @return true if the config is supported by framework.
     */
    private boolean isLocalImsConfigKey(int key) {
        return Arrays.stream(LOCAL_IMS_CONFIG_KEYS).anyMatch(value -> value == key);
    }

    private boolean isVoImsOptInEnabled() {
        int setting = mSubscriptionManagerProxy.getIntegerSubscriptionProperty(
                getSubId(), SubscriptionManager.VOIMS_OPT_IN_STATUS,
                SUB_PROPERTY_NOT_INITIALIZED);
        return (setting == ProvisioningManager.PROVISIONING_VALUE_ENABLED);
    }

    private int setVoImsOptInSetting(int value) {
        mSubscriptionManagerProxy.setSubscriptionProperty(
                getSubId(),
                SubscriptionManager.VOIMS_OPT_IN_STATUS,
                String.valueOf(value));
        return ImsConfig.OperationStatusConstants.SUCCESS;
    }

    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        pw.println("ImsManager:");
        pw.println("  device supports IMS = " + isImsSupportedOnDevice(mContext));
        pw.println("  mPhoneId = " + mPhoneId);
        pw.println("  mConfigUpdated = " + mConfigUpdated);
        pw.println("  mImsServiceProxy = " + mMmTelConnectionRef.get());
        pw.println("  mDataEnabled = " + isDataEnabled());
        pw.println("  ignoreDataEnabledChanged = " + getBooleanCarrierConfig(
                CarrierConfigManager.KEY_IGNORE_DATA_ENABLED_CHANGED_FOR_VIDEO_CALLS));

        pw.println("  isGbaValid = " + isGbaValid());
        pw.println("  isImsTurnOffAllowed = " + isImsTurnOffAllowed());
        pw.println("  isNonTtyOrTtyOnVolteEnabled = " + isNonTtyOrTtyOnVolteEnabled());

        pw.println("  isVolteEnabledByPlatform = " + isVolteEnabledByPlatform());
        pw.println("  isVoImsOptInEnabled = " + isVoImsOptInEnabled());
        pw.println("  isVolteProvisionedOnDevice = " + isVolteProvisionedOnDevice());
        pw.println("  isEnhanced4gLteModeSettingEnabledByUser = " +
                isEnhanced4gLteModeSettingEnabledByUser());
        pw.println("  isVtEnabledByPlatform = " + isVtEnabledByPlatform());
        pw.println("  isVtEnabledByUser = " + isVtEnabledByUser());

        pw.println("  isWfcEnabledByPlatform = " + isWfcEnabledByPlatform());
        pw.println("  isWfcEnabledByUser = " + isWfcEnabledByUser());
        pw.println("  getWfcMode(non-roaming) = " + getWfcMode(false));
        pw.println("  getWfcMode(roaming) = " + getWfcMode(true));
        pw.println("  isWfcRoamingEnabledByUser = " + isWfcRoamingEnabledByUser());

        pw.println("  isVtProvisionedOnDevice = " + isVtProvisionedOnDevice());
        pw.println("  isWfcProvisionedOnDevice = " + isWfcProvisionedOnDevice());

        pw.println("  isCrossSimEnabledByPlatform = " + isCrossSimEnabledByPlatform());
        pw.println("  isCrossSimCallingEnabledByUser = " + isCrossSimCallingEnabledByUser());
        pw.println("  isImsOverNrEnabledByPlatform = " + isImsOverNrEnabledByPlatform());
        pw.flush();
    }

    /**
     * Determines if a sub id is valid.
     * Mimics the logic in SubscriptionController.validateSubId.
     * @param subId The sub id to check.
     * @return {@code true} if valid, {@code false} otherwise.
     */
    private boolean isSubIdValid(int subId) {
        return mSubscriptionManagerProxy.isValidSubscriptionId(subId) &&
                subId != SubscriptionManager.DEFAULT_SUBSCRIPTION_ID;
    }

    private boolean isActiveSubscriptionPresent() {
        return mSubscriptionManagerProxy.getActiveSubscriptionIdList().length > 0;
    }

    private void updateImsCarrierConfigs(PersistableBundle configs) throws ImsException {
        MmTelFeatureConnection c = getOrThrowExceptionIfServiceUnavailable();

        IImsConfig config = c.getConfig();
        if (config == null) {
            throw new ImsException("getConfigInterface()",
                    ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE);
        }
        try {
            config.updateImsCarrierConfigs(configs);
        } catch (RemoteException e) {
            throw new ImsException("updateImsCarrierConfigs()", e,
                    ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN);
        }
    }
}