aboutsummaryrefslogtreecommitdiff
path: root/bumble/avdtp.py
blob: 3988f30905c3c0db7bc90d99f5f628365ecfb640 (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
# Copyright 2021-2022 Google LLC
#
# 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
#
#      https://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.

# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
from __future__ import annotations
import asyncio
import struct
import time
import logging
from pyee import EventEmitter
from typing import Dict, Type

from .core import (
    BT_ADVANCED_AUDIO_DISTRIBUTION_SERVICE,
    InvalidStateError,
    ProtocolError,
    name_or_number,
)
from .a2dp import (
    A2DP_CODEC_TYPE_NAMES,
    A2DP_MPEG_2_4_AAC_CODEC_TYPE,
    A2DP_NON_A2DP_CODEC_TYPE,
    A2DP_SBC_CODEC_TYPE,
    AacMediaCodecInformation,
    SbcMediaCodecInformation,
    VendorSpecificMediaCodecInformation,
)
from . import sdp
from .colors import color

# -----------------------------------------------------------------------------
# Logging
# -----------------------------------------------------------------------------
logger = logging.getLogger(__name__)


# -----------------------------------------------------------------------------
# Constants
# -----------------------------------------------------------------------------
# fmt: off
# pylint: disable=line-too-long

AVDTP_PSM = 0x0019

AVDTP_DEFAULT_RTX_SIG_TIMER = 5  # Seconds

# Signal Identifiers (AVDTP spec - 8.5 Signal Command Set)
AVDTP_DISCOVER             = 0x01
AVDTP_GET_CAPABILITIES     = 0x02
AVDTP_SET_CONFIGURATION    = 0x03
AVDTP_GET_CONFIGURATION    = 0x04
AVDTP_RECONFIGURE          = 0x05
AVDTP_OPEN                 = 0x06
AVDTP_START                = 0x07
AVDTP_CLOSE                = 0x08
AVDTP_SUSPEND              = 0x09
AVDTP_ABORT                = 0x0A
AVDTP_SECURITY_CONTROL     = 0x0B
AVDTP_GET_ALL_CAPABILITIES = 0x0C
AVDTP_DELAYREPORT          = 0x0D

AVDTP_SIGNAL_NAMES = {
    AVDTP_DISCOVER:             'AVDTP_DISCOVER',
    AVDTP_GET_CAPABILITIES:     'AVDTP_GET_CAPABILITIES',
    AVDTP_SET_CONFIGURATION:    'AVDTP_SET_CONFIGURATION',
    AVDTP_GET_CONFIGURATION:    'AVDTP_GET_CONFIGURATION',
    AVDTP_RECONFIGURE:          'AVDTP_RECONFIGURE',
    AVDTP_OPEN:                 'AVDTP_OPEN',
    AVDTP_START:                'AVDTP_START',
    AVDTP_CLOSE:                'AVDTP_CLOSE',
    AVDTP_SUSPEND:              'AVDTP_SUSPEND',
    AVDTP_ABORT:                'AVDTP_ABORT',
    AVDTP_SECURITY_CONTROL:     'AVDTP_SECURITY_CONTROL',
    AVDTP_GET_ALL_CAPABILITIES: 'AVDTP_GET_ALL_CAPABILITIES',
    AVDTP_DELAYREPORT:          'AVDTP_DELAYREPORT'
}

AVDTP_SIGNAL_IDENTIFIERS = {
    'AVDTP_DISCOVER':             AVDTP_DISCOVER,
    'AVDTP_GET_CAPABILITIES':     AVDTP_GET_CAPABILITIES,
    'AVDTP_SET_CONFIGURATION':    AVDTP_SET_CONFIGURATION,
    'AVDTP_GET_CONFIGURATION':    AVDTP_GET_CONFIGURATION,
    'AVDTP_RECONFIGURE':          AVDTP_RECONFIGURE,
    'AVDTP_OPEN':                 AVDTP_OPEN,
    'AVDTP_START':                AVDTP_START,
    'AVDTP_CLOSE':                AVDTP_CLOSE,
    'AVDTP_SUSPEND':              AVDTP_SUSPEND,
    'AVDTP_ABORT':                AVDTP_ABORT,
    'AVDTP_SECURITY_CONTROL':     AVDTP_SECURITY_CONTROL,
    'AVDTP_GET_ALL_CAPABILITIES': AVDTP_GET_ALL_CAPABILITIES,
    'AVDTP_DELAYREPORT':          AVDTP_DELAYREPORT
}

# Error codes (AVDTP spec - 8.20.6.2 ERROR_CODE tables)
AVDTP_BAD_HEADER_FORMAT_ERROR          = 0x01
AVDTP_BAD_LENGTH_ERROR                 = 0x11
AVDTP_BAD_ACP_SEID_ERROR               = 0x12
AVDTP_SEP_IN_USE_ERROR                 = 0x13
AVDTP_SEP_NOT_IN_USE_ERROR             = 0x14
AVDTP_BAD_SERV_CATEGORY_ERROR          = 0x17
AVDTP_BAD_PAYLOAD_FORMAT_ERROR         = 0x18
AVDTP_NOT_SUPPORTED_COMMAND_ERROR      = 0x19
AVDTP_INVALID_CAPABILITIES_ERROR       = 0x1A
AVDTP_BAD_RECOVERY_TYPE_ERROR          = 0x22
AVDTP_BAD_MEDIA_TRANSPORT_FORMAT_ERROR = 0x23
AVDTP_BAD_RECOVERY_FORMAT_ERROR        = 0x25
AVDTP_BAD_ROHC_FORMAT_ERROR            = 0x26
AVDTP_BAD_CP_FORMAT_ERROR              = 0x27
AVDTP_BAD_MULTIPLEXING_FORMAT_ERROR    = 0x28
AVDTP_UNSUPPORTED_CONFIGURATION_ERROR  = 0x29
AVDTP_BAD_STATE_ERROR                  = 0x31

AVDTP_ERROR_NAMES = {
    AVDTP_BAD_HEADER_FORMAT_ERROR:          'AVDTP_BAD_HEADER_FORMAT_ERROR',
    AVDTP_BAD_LENGTH_ERROR:                 'AVDTP_BAD_LENGTH_ERROR',
    AVDTP_BAD_ACP_SEID_ERROR:               'AVDTP_BAD_ACP_SEID_ERROR',
    AVDTP_SEP_IN_USE_ERROR:                 'AVDTP_SEP_IN_USE_ERROR',
    AVDTP_SEP_NOT_IN_USE_ERROR:             'AVDTP_SEP_NOT_IN_USE_ERROR',
    AVDTP_BAD_SERV_CATEGORY_ERROR:          'AVDTP_BAD_SERV_CATEGORY_ERROR',
    AVDTP_BAD_PAYLOAD_FORMAT_ERROR:         'AVDTP_BAD_PAYLOAD_FORMAT_ERROR',
    AVDTP_NOT_SUPPORTED_COMMAND_ERROR:      'AVDTP_NOT_SUPPORTED_COMMAND_ERROR',
    AVDTP_INVALID_CAPABILITIES_ERROR:       'AVDTP_INVALID_CAPABILITIES_ERROR',
    AVDTP_BAD_RECOVERY_TYPE_ERROR:          'AVDTP_BAD_RECOVERY_TYPE_ERROR',
    AVDTP_BAD_MEDIA_TRANSPORT_FORMAT_ERROR: 'AVDTP_BAD_MEDIA_TRANSPORT_FORMAT_ERROR',
    AVDTP_BAD_RECOVERY_FORMAT_ERROR:        'AVDTP_BAD_RECOVERY_FORMAT_ERROR',
    AVDTP_BAD_ROHC_FORMAT_ERROR:            'AVDTP_BAD_ROHC_FORMAT_ERROR',
    AVDTP_BAD_CP_FORMAT_ERROR:              'AVDTP_BAD_CP_FORMAT_ERROR',
    AVDTP_BAD_MULTIPLEXING_FORMAT_ERROR:    'AVDTP_BAD_MULTIPLEXING_FORMAT_ERROR',
    AVDTP_UNSUPPORTED_CONFIGURATION_ERROR:  'AVDTP_UNSUPPORTED_CONFIGURATION_ERROR',
    AVDTP_BAD_STATE_ERROR:                  'AVDTP_BAD_STATE_ERROR'
}

AVDTP_AUDIO_MEDIA_TYPE      = 0x00
AVDTP_VIDEO_MEDIA_TYPE      = 0x01
AVDTP_MULTIMEDIA_MEDIA_TYPE = 0x02

AVDTP_MEDIA_TYPE_NAMES = {
    AVDTP_AUDIO_MEDIA_TYPE:      'AVDTP_AUDIO_MEDIA_TYPE',
    AVDTP_VIDEO_MEDIA_TYPE:      'AVDTP_VIDEO_MEDIA_TYPE',
    AVDTP_MULTIMEDIA_MEDIA_TYPE: 'AVDTP_MULTIMEDIA_MEDIA_TYPE'
}

# TSEP (AVDTP spec - 8.20.3 Stream End-point Type, Source or Sink (TSEP))
AVDTP_TSEP_SRC = 0x00
AVDTP_TSEP_SNK = 0x01

AVDTP_TSEP_NAMES = {
    AVDTP_TSEP_SRC: 'AVDTP_TSEP_SRC',
    AVDTP_TSEP_SNK: 'AVDTP_TSEP_SNK'
}

# Service Categories (AVDTP spec - Table 8.47: Service Category information element field values)
AVDTP_MEDIA_TRANSPORT_SERVICE_CATEGORY    = 0x01
AVDTP_REPORTING_SERVICE_CATEGORY          = 0x02
AVDTP_RECOVERY_SERVICE_CATEGORY           = 0x03
AVDTP_CONTENT_PROTECTION_SERVICE_CATEGORY = 0x04
AVDTP_HEADER_COMPRESSION_SERVICE_CATEGORY = 0x05
AVDTP_MULTIPLEXING_SERVICE_CATEGORY       = 0x06
AVDTP_MEDIA_CODEC_SERVICE_CATEGORY        = 0x07
AVDTP_DELAY_REPORTING_SERVICE_CATEGORY    = 0x08

AVDTP_SERVICE_CATEGORY_NAMES = {
    AVDTP_MEDIA_TRANSPORT_SERVICE_CATEGORY:    'AVDTP_MEDIA_TRANSPORT_SERVICE_CATEGORY',
    AVDTP_REPORTING_SERVICE_CATEGORY:          'AVDTP_REPORTING_SERVICE_CATEGORY',
    AVDTP_RECOVERY_SERVICE_CATEGORY:           'AVDTP_RECOVERY_SERVICE_CATEGORY',
    AVDTP_CONTENT_PROTECTION_SERVICE_CATEGORY: 'AVDTP_CONTENT_PROTECTION_SERVICE_CATEGORY',
    AVDTP_HEADER_COMPRESSION_SERVICE_CATEGORY: 'AVDTP_HEADER_COMPRESSION_SERVICE_CATEGORY',
    AVDTP_MULTIPLEXING_SERVICE_CATEGORY:       'AVDTP_MULTIPLEXING_SERVICE_CATEGORY',
    AVDTP_MEDIA_CODEC_SERVICE_CATEGORY:        'AVDTP_MEDIA_CODEC_SERVICE_CATEGORY',
    AVDTP_DELAY_REPORTING_SERVICE_CATEGORY:    'AVDTP_DELAY_REPORTING_SERVICE_CATEGORY'
}

# States (AVDTP spec - 9.1 State Definitions)
AVDTP_IDLE_STATE       = 0x00
AVDTP_CONFIGURED_STATE = 0x01
AVDTP_OPEN_STATE       = 0x02
AVDTP_STREAMING_STATE  = 0x03
AVDTP_CLOSING_STATE    = 0x04
AVDTP_ABORTING_STATE   = 0x05

AVDTP_STATE_NAMES = {
    AVDTP_IDLE_STATE:       'AVDTP_IDLE_STATE',
    AVDTP_CONFIGURED_STATE: 'AVDTP_CONFIGURED_STATE',
    AVDTP_OPEN_STATE:       'AVDTP_OPEN_STATE',
    AVDTP_STREAMING_STATE:  'AVDTP_STREAMING_STATE',
    AVDTP_CLOSING_STATE:    'AVDTP_CLOSING_STATE',
    AVDTP_ABORTING_STATE:   'AVDTP_ABORTING_STATE'
}

# fmt: on
# pylint: enable=line-too-long
# pylint: disable=invalid-name


# -----------------------------------------------------------------------------
async def find_avdtp_service_with_sdp_client(sdp_client):
    '''
    Find an AVDTP service, using a connected SDP client, and return its version,
    or None if none is found
    '''

    # Search for services with an Audio Sink service class
    search_result = await sdp_client.search_attributes(
        [BT_ADVANCED_AUDIO_DISTRIBUTION_SERVICE],
        [sdp.SDP_BLUETOOTH_PROFILE_DESCRIPTOR_LIST_ATTRIBUTE_ID],
    )
    for attribute_list in search_result:
        profile_descriptor_list = sdp.ServiceAttribute.find_attribute_in_list(
            attribute_list, sdp.SDP_BLUETOOTH_PROFILE_DESCRIPTOR_LIST_ATTRIBUTE_ID
        )
        if profile_descriptor_list:
            for profile_descriptor in profile_descriptor_list.value:
                if len(profile_descriptor.value) >= 2:
                    avdtp_version_major = profile_descriptor.value[1].value >> 8
                    avdtp_version_minor = profile_descriptor.value[1].value & 0xFF
                    return (avdtp_version_major, avdtp_version_minor)


# -----------------------------------------------------------------------------
async def find_avdtp_service_with_connection(device, connection):
    '''
    Find an AVDTP service, for a connection, and return its version,
    or None if none is found
    '''

    sdp_client = sdp.Client(device)
    await sdp_client.connect(connection)
    service_version = await find_avdtp_service_with_sdp_client(sdp_client)
    await sdp_client.disconnect()

    return service_version


# -----------------------------------------------------------------------------
class RealtimeClock:
    def now(self):
        return time.time()

    async def sleep(self, duration):
        await asyncio.sleep(duration)


# -----------------------------------------------------------------------------
class MediaPacket:
    @staticmethod
    def from_bytes(data):
        version = (data[0] >> 6) & 0x03
        padding = (data[0] >> 5) & 0x01
        extension = (data[0] >> 4) & 0x01
        csrc_count = data[0] & 0x0F
        marker = (data[1] >> 7) & 0x01
        payload_type = data[1] & 0x7F
        sequence_number = struct.unpack_from('>H', data, 2)[0]
        timestamp = struct.unpack_from('>I', data, 4)[0]
        ssrc = struct.unpack_from('>I', data, 8)[0]
        csrc_list = [
            struct.unpack_from('>I', data, 12 + i)[0] for i in range(csrc_count)
        ]
        payload = data[12 + csrc_count * 4 :]

        return MediaPacket(
            version,
            padding,
            extension,
            marker,
            sequence_number,
            timestamp,
            ssrc,
            csrc_list,
            payload_type,
            payload,
        )

    def __init__(
        self,
        version,
        padding,
        extension,
        marker,
        sequence_number,
        timestamp,
        ssrc,
        csrc_list,
        payload_type,
        payload,
    ):
        self.version = version
        self.padding = padding
        self.extension = extension
        self.marker = marker
        self.sequence_number = sequence_number
        self.timestamp = timestamp
        self.ssrc = ssrc
        self.csrc_list = csrc_list
        self.payload_type = payload_type
        self.payload = payload

    def __bytes__(self):
        header = bytes(
            [
                self.version << 6
                | self.padding << 5
                | self.extension << 4
                | len(self.csrc_list),
                self.marker << 7 | self.payload_type,
            ]
        ) + struct.pack('>HII', self.sequence_number, self.timestamp, self.ssrc)
        for csrc in self.csrc_list:
            header += struct.pack('>I', csrc)
        return header + self.payload

    def __str__(self):
        return (
            f'RTP(v={self.version},'
            f'p={self.padding},'
            f'x={self.extension},'
            f'm={self.marker},'
            f'pt={self.payload_type},'
            f'sn={self.sequence_number},'
            f'ts={self.timestamp},'
            f'ssrc={self.ssrc},'
            f'csrcs={self.csrc_list},'
            f'payload_size={len(self.payload)})'
        )


# -----------------------------------------------------------------------------
class MediaPacketPump:
    def __init__(self, packets, clock=RealtimeClock()):
        self.packets = packets
        self.clock = clock
        self.pump_task = None

    async def start(self, rtp_channel):
        async def pump_packets():
            start_time = 0
            start_timestamp = 0

            try:
                logger.debug('pump starting')
                async for packet in self.packets:
                    # Capture the timestamp of the first packet
                    if start_time == 0:
                        start_time = self.clock.now()
                        start_timestamp = packet.timestamp_seconds

                    # Wait until we can send
                    when = start_time + (packet.timestamp_seconds - start_timestamp)
                    now = self.clock.now()
                    if when > now:
                        delay = when - now
                        logger.debug(f'waiting for {delay}')
                        await self.clock.sleep(delay)

                    # Emit
                    rtp_channel.send_pdu(bytes(packet))
                    logger.debug(
                        f'{color(">>> sending RTP packet:", "green")} {packet}'
                    )
            except asyncio.exceptions.CancelledError:
                logger.debug('pump canceled')

        # Pump packets
        self.pump_task = asyncio.create_task(pump_packets())

    async def stop(self):
        # Stop the pump
        if self.pump_task:
            self.pump_task.cancel()
            await self.pump_task
            self.pump_task = None


# -----------------------------------------------------------------------------
class MessageAssembler:  # pylint: disable=attribute-defined-outside-init
    def __init__(self, callback):
        self.callback = callback
        self.reset()

    def reset(self):
        self.transaction_label = 0
        self.message = None
        self.message_type = 0
        self.signal_identifier = 0
        self.number_of_signal_packets = 0
        self.packet_count = 0

    def on_pdu(self, pdu):
        self.packet_count += 1

        transaction_label = pdu[0] >> 4
        packet_type = (pdu[0] >> 2) & 3
        message_type = pdu[0] & 3

        logger.debug(
            f'transaction_label={transaction_label}, '
            f'packet_type={Protocol.packet_type_name(packet_type)}, '
            f'message_type={Message.message_type_name(message_type)}'
        )
        if packet_type in (Protocol.SINGLE_PACKET, Protocol.START_PACKET):
            if self.message is not None:
                # The previous message has not been terminated
                logger.warning(
                    'received a start or single packet when expecting an end or '
                    'continuation'
                )
                self.reset()

            self.transaction_label = transaction_label
            self.signal_identifier = pdu[1] & 0x3F
            self.message_type = message_type

            if packet_type == Protocol.SINGLE_PACKET:
                self.message = pdu[2:]
                self.on_message_complete()
            else:
                self.number_of_signal_packets = pdu[2]
                self.message = pdu[3:]
        elif packet_type in (Protocol.CONTINUE_PACKET, Protocol.END_PACKET):
            if self.packet_count == 0:
                logger.warning('unexpected continuation')
                return

            if transaction_label != self.transaction_label:
                logger.warning(
                    f'transaction label mismatch: expected {self.transaction_label}, '
                    f'received {transaction_label}'
                )
                return

            if message_type != self.message_type:
                logger.warning(
                    f'message type mismatch: expected {self.message_type}, '
                    f'received {message_type}'
                )
                return

            self.message += pdu[1:]

            if packet_type == Protocol.END_PACKET:
                if self.packet_count != self.number_of_signal_packets:
                    logger.warning(
                        'incomplete fragmented message: '
                        f'expected {self.number_of_signal_packets} packets, '
                        f'received {self.packet_count}'
                    )
                    self.reset()
                    return

                self.on_message_complete()
            else:
                if self.packet_count > self.number_of_signal_packets:
                    logger.warning(
                        'too many packets: '
                        f'expected {self.number_of_signal_packets}, '
                        f'received {self.packet_count}'
                    )
                    self.reset()
                    return

    def on_message_complete(self):
        message = Message.create(
            self.signal_identifier, self.message_type, self.message
        )

        try:
            self.callback(self.transaction_label, message)
        except Exception as error:
            logger.warning(color(f'!!! exception in callback: {error}'))

        self.reset()


# -----------------------------------------------------------------------------
class ServiceCapabilities:
    @staticmethod
    def create(service_category, service_capabilities_bytes):
        # Select the appropriate subclass
        if service_category == AVDTP_MEDIA_CODEC_SERVICE_CATEGORY:
            cls = MediaCodecCapabilities
        else:
            cls = ServiceCapabilities

        # Create an instance and initialize it
        instance = cls.__new__(cls)
        instance.service_category = service_category
        instance.service_capabilities_bytes = service_capabilities_bytes
        instance.init_from_bytes()

        return instance

    @staticmethod
    def parse_capabilities(payload):
        capabilities = []
        while payload:
            service_category = payload[0]
            length_of_service_capabilities = payload[1]
            service_capabilities_bytes = payload[2 : 2 + length_of_service_capabilities]
            capabilities.append(
                ServiceCapabilities.create(service_category, service_capabilities_bytes)
            )

            payload = payload[2 + length_of_service_capabilities :]

        return capabilities

    @staticmethod
    def serialize_capabilities(capabilities):
        serialized = b''
        for item in capabilities:
            serialized += (
                bytes([item.service_category, len(item.service_capabilities_bytes)])
                + item.service_capabilities_bytes
            )
        return serialized

    def init_from_bytes(self):
        pass

    def __init__(self, service_category, service_capabilities_bytes=b''):
        self.service_category = service_category
        self.service_capabilities_bytes = service_capabilities_bytes

    def to_string(self, details=[]):  # pylint: disable=dangerous-default-value
        attributes = ','.join(
            [name_or_number(AVDTP_SERVICE_CATEGORY_NAMES, self.service_category)]
            + details
        )
        return f'ServiceCapabilities({attributes})'

    def __str__(self):
        if self.service_capabilities_bytes:
            details = [self.service_capabilities_bytes.hex()]
        else:
            details = []
        return self.to_string(details)


# -----------------------------------------------------------------------------
class MediaCodecCapabilities(ServiceCapabilities):
    def init_from_bytes(self):
        self.media_type = self.service_capabilities_bytes[0]
        self.media_codec_type = self.service_capabilities_bytes[1]
        self.media_codec_information = self.service_capabilities_bytes[2:]

        if self.media_codec_type == A2DP_SBC_CODEC_TYPE:
            self.media_codec_information = SbcMediaCodecInformation.from_bytes(
                self.media_codec_information
            )
        elif self.media_codec_type == A2DP_MPEG_2_4_AAC_CODEC_TYPE:
            self.media_codec_information = AacMediaCodecInformation.from_bytes(
                self.media_codec_information
            )
        elif self.media_codec_type == A2DP_NON_A2DP_CODEC_TYPE:
            self.media_codec_information = (
                VendorSpecificMediaCodecInformation.from_bytes(
                    self.media_codec_information
                )
            )

    def __init__(self, media_type, media_codec_type, media_codec_information):
        super().__init__(
            AVDTP_MEDIA_CODEC_SERVICE_CATEGORY,
            bytes([media_type, media_codec_type]) + bytes(media_codec_information),
        )
        self.media_type = media_type
        self.media_codec_type = media_codec_type
        self.media_codec_information = media_codec_information

    def __str__(self):
        codec_info = (
            self.media_codec_information.hex()
            if isinstance(self.media_codec_information, bytes)
            else str(self.media_codec_information)
        )

        details = [
            f'media_type={name_or_number(AVDTP_MEDIA_TYPE_NAMES, self.media_type)}',
            f'codec={name_or_number(A2DP_CODEC_TYPE_NAMES, self.media_codec_type)}',
            f'codec_info={codec_info}',
        ]
        return self.to_string(details)


# -----------------------------------------------------------------------------
class EndPointInfo:
    @staticmethod
    def from_bytes(payload):
        return EndPointInfo(
            payload[0] >> 2, payload[0] >> 1 & 1, payload[1] >> 4, payload[1] >> 3 & 1
        )

    def __bytes__(self):
        return bytes(
            [self.seid << 2 | self.in_use << 1, self.media_type << 4 | self.tsep << 3]
        )

    def __init__(self, seid, in_use, media_type, tsep):
        self.seid = seid
        self.in_use = in_use
        self.media_type = media_type
        self.tsep = tsep


# -----------------------------------------------------------------------------
class Message:  # pylint:disable=attribute-defined-outside-init
    COMMAND = 0
    GENERAL_REJECT = 1
    RESPONSE_ACCEPT = 2
    RESPONSE_REJECT = 3

    MESSAGE_TYPE_NAMES = {
        COMMAND: 'COMMAND',
        GENERAL_REJECT: 'GENERAL_REJECT',
        RESPONSE_ACCEPT: 'RESPONSE_ACCEPT',
        RESPONSE_REJECT: 'RESPONSE_REJECT',
    }

    # Subclasses, by signal identifier and message type
    subclasses: Dict[int, Dict[int, Type[Message]]] = {}

    @staticmethod
    def message_type_name(message_type):
        return name_or_number(Message.MESSAGE_TYPE_NAMES, message_type)

    @staticmethod
    def subclass(subclass):
        # Infer the signal identifier and message subtype from the class name
        name = subclass.__name__
        if name == 'General_Reject':
            subclass.signal_identifier = 0
            signal_identifier_str = None
            message_type = Message.COMMAND
        elif name.endswith('_Command'):
            signal_identifier_str = name[:-8]
            message_type = Message.COMMAND
        elif name.endswith('_Response'):
            signal_identifier_str = name[:-9]
            message_type = Message.RESPONSE_ACCEPT
        elif name.endswith('_Reject'):
            signal_identifier_str = name[:-7]
            message_type = Message.RESPONSE_REJECT
        else:
            raise ValueError('invalid class name')

        subclass.message_type = message_type

        if signal_identifier_str is not None:
            for (name, signal_identifier) in AVDTP_SIGNAL_IDENTIFIERS.items():
                if name.lower().endswith(signal_identifier_str.lower()):
                    subclass.signal_identifier = signal_identifier
                    break

            # Register the subclass
            Message.subclasses.setdefault(subclass.signal_identifier, {})[
                subclass.message_type
            ] = subclass

        return subclass

    # Factory method to create a subclass based on the signal identifier and message
    # type
    @staticmethod
    def create(signal_identifier, message_type, payload):
        # Look for a registered subclass
        subclasses = Message.subclasses.get(signal_identifier)
        if subclasses:
            subclass = subclasses.get(message_type)
            if subclass:
                instance = subclass.__new__(subclass)
                instance.payload = payload
                instance.init_from_payload()
                return instance

        # Instantiate the appropriate class based on the message type
        if message_type == Message.RESPONSE_REJECT:
            # Assume a simple reject message
            instance = Simple_Reject(payload)
            instance.init_from_payload()
        else:
            instance = Message(payload)
        instance.signal_identifier = signal_identifier
        instance.message_type = message_type
        return instance

    def init_from_payload(self):
        pass

    def __init__(self, payload=b''):
        self.payload = payload

    def to_string(self, details):
        base = color(
            f'{name_or_number(AVDTP_SIGNAL_NAMES, self.signal_identifier)}_'
            f'{Message.message_type_name(self.message_type)}',
            'yellow',
        )

        if details:
            if isinstance(details, str):
                return f'{base}: {details}'

            return (
                base
                + ':\n'
                + '\n'.join(['  ' + color(detail, 'cyan') for detail in details])
            )

        return base

    def __str__(self):
        return self.to_string(self.payload.hex())


# -----------------------------------------------------------------------------
class Simple_Command(Message):
    '''
    Command message with just one seid
    '''

    def init_from_payload(self):
        self.acp_seid = self.payload[0] >> 2

    def __init__(self, seid):
        super().__init__(payload=bytes([seid << 2]))
        self.acp_seid = seid

    def __str__(self):
        return self.to_string([f'ACP SEID: {self.acp_seid}'])


# -----------------------------------------------------------------------------
class Simple_Reject(Message):
    '''
    Reject messages with just an error code
    '''

    def init_from_payload(self):
        self.error_code = self.payload[0]

    def __init__(self, error_code):
        super().__init__(payload=bytes([error_code]))
        self.error_code = error_code

    def __str__(self):
        details = [f'error_code: {name_or_number(AVDTP_ERROR_NAMES, self.error_code)}']
        return self.to_string(details)


# -----------------------------------------------------------------------------
@Message.subclass
class Discover_Command(Message):
    '''
    See Bluetooth AVDTP spec - 8.6.1 Stream End Point Discovery Command
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Discover_Response(Message):
    '''
    See Bluetooth AVDTP spec - 8.6.2 Stream End Point Discovery Response
    '''

    def init_from_payload(self):
        self.endpoints = []
        endpoint_count = len(self.payload) // 2
        for i in range(endpoint_count):
            self.endpoints.append(
                EndPointInfo.from_bytes(self.payload[i * 2 : (i + 1) * 2])
            )

    def __init__(self, endpoints):
        super().__init__(payload=b''.join([bytes(endpoint) for endpoint in endpoints]))
        self.endpoints = endpoints

    def __str__(self):
        details = []
        for endpoint in self.endpoints:
            details.extend(
                # pylint: disable=line-too-long
                [
                    f'ACP SEID: {endpoint.seid}',
                    f'  in_use:     {endpoint.in_use}',
                    f'  media_type: {name_or_number(AVDTP_MEDIA_TYPE_NAMES, endpoint.media_type)}',
                    f'  tsep:       {name_or_number(AVDTP_TSEP_NAMES, endpoint.tsep)}',
                ]
            )
        return self.to_string(details)


# -----------------------------------------------------------------------------
@Message.subclass
class Get_Capabilities_Command(Simple_Command):
    '''
    See Bluetooth AVDTP spec - 8.7.1 Get Capabilities Command
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Get_Capabilities_Response(Message):
    '''
    See Bluetooth AVDTP spec - 8.7.2 Get All Capabilities Response
    '''

    def init_from_payload(self):
        self.capabilities = ServiceCapabilities.parse_capabilities(self.payload)

    def __init__(self, capabilities):
        super().__init__(
            payload=ServiceCapabilities.serialize_capabilities(capabilities)
        )
        self.capabilities = capabilities

    def __str__(self):
        details = [str(capability) for capability in self.capabilities]
        return self.to_string(details)


# -----------------------------------------------------------------------------
@Message.subclass
class Get_Capabilities_Reject(Simple_Reject):
    '''
    See Bluetooth AVDTP spec - 8.7.3 Get Capabilities Reject
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Get_All_Capabilities_Command(Get_Capabilities_Command):
    '''
    See Bluetooth AVDTP spec - 8.8.1 Get All Capabilities Command
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Get_All_Capabilities_Response(Get_Capabilities_Response):
    '''
    See Bluetooth AVDTP spec - 8.8.2 Get All Capabilities Response
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Get_All_Capabilities_Reject(Simple_Reject):
    '''
    See Bluetooth AVDTP spec - 8.8.3 Get All Capabilities Reject
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Set_Configuration_Command(Message):
    '''
    See Bluetooth AVDTP spec - 8.9.1 Set Configuration Command
    '''

    def init_from_payload(self):
        self.acp_seid = self.payload[0] >> 2
        self.int_seid = self.payload[1] >> 2
        self.capabilities = ServiceCapabilities.parse_capabilities(self.payload[2:])

    def __init__(self, acp_seid, int_seid, capabilities):
        super().__init__(
            payload=bytes([acp_seid << 2, int_seid << 2])
            + ServiceCapabilities.serialize_capabilities(capabilities)
        )
        self.acp_seid = acp_seid
        self.int_seid = int_seid
        self.capabilities = capabilities

    def __str__(self):
        details = [f'ACP SEID: {self.acp_seid}', f'INT SEID: {self.int_seid}'] + [
            str(capability) for capability in self.capabilities
        ]
        return self.to_string(details)


# -----------------------------------------------------------------------------
@Message.subclass
class Set_Configuration_Response(Message):
    '''
    See Bluetooth AVDTP spec - 8.9.2 Set Configuration Response
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Set_Configuration_Reject(Message):
    '''
    See Bluetooth AVDTP spec - 8.9.3 Set Configuration Reject
    '''

    def init_from_payload(self):
        self.service_category = self.payload[0]
        self.error_code = self.payload[1]

    def __init__(self, service_category, error_code):
        super().__init__(payload=bytes([service_category, error_code]))
        self.service_category = service_category
        self.error_code = error_code

    def __str__(self):
        details = [
            (
                'service_category: '
                f'{name_or_number(AVDTP_SERVICE_CATEGORY_NAMES, self.service_category)}'
            ),
            (
                'error_code:       '
                f'{name_or_number(AVDTP_ERROR_NAMES, self.error_code)}'
            ),
        ]
        return self.to_string(details)


# -----------------------------------------------------------------------------
@Message.subclass
class Get_Configuration_Command(Simple_Command):
    '''
    See Bluetooth AVDTP spec - 8.10.1 Get Configuration Command
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Get_Configuration_Response(Message):
    '''
    See Bluetooth AVDTP spec - 8.10.2 Get Configuration Response
    '''

    def init_from_payload(self):
        self.capabilities = ServiceCapabilities.parse_capabilities(self.payload)

    def __init__(self, capabilities):
        super().__init__(
            payload=ServiceCapabilities.serialize_capabilities(capabilities)
        )
        self.capabilities = capabilities

    def __str__(self):
        details = [str(capability) for capability in self.capabilities]
        return self.to_string(details)


# -----------------------------------------------------------------------------
@Message.subclass
class Get_Configuration_Reject(Simple_Reject):
    '''
    See Bluetooth AVDTP spec - 8.10.3 Get Configuration Reject
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Reconfigure_Command(Message):
    '''
    See Bluetooth AVDTP spec - 8.11.1 Reconfigure Command
    '''

    def init_from_payload(self):
        # pylint: disable=attribute-defined-outside-init
        self.acp_seid = self.payload[0] >> 2
        self.capabilities = ServiceCapabilities.parse_capabilities(self.payload[1:])

    def __str__(self):
        details = [
            f'ACP SEID: {self.acp_seid}',
        ] + [str(capability) for capability in self.capabilities]
        return self.to_string(details)


# -----------------------------------------------------------------------------
@Message.subclass
class Reconfigure_Response(Message):
    '''
    See Bluetooth AVDTP spec - 8.11.2 Reconfigure Response
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Reconfigure_Reject(Set_Configuration_Reject):
    '''
    See Bluetooth AVDTP spec - 8.11.3 Reconfigure Reject
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Open_Command(Simple_Command):
    '''
    See Bluetooth AVDTP spec - 8.12.1 Open Stream Command
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Open_Response(Message):
    '''
    See Bluetooth AVDTP spec - 8.12.2 Open Stream Response
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Open_Reject(Simple_Reject):
    '''
    See Bluetooth AVDTP spec - 8.12.3 Open Stream Reject
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Start_Command(Message):
    '''
    See Bluetooth AVDTP spec - 8.13.1 Start Stream Command
    '''

    def init_from_payload(self):
        self.acp_seids = [x >> 2 for x in self.payload]

    def __init__(self, seids):
        super().__init__(payload=bytes([seid << 2 for seid in seids]))
        self.acp_seids = seids

    def __str__(self):
        return self.to_string([f'ACP SEIDs: {self.acp_seids}'])


# -----------------------------------------------------------------------------
@Message.subclass
class Start_Response(Message):
    '''
    See Bluetooth AVDTP spec - 8.13.2 Start Stream Response
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Start_Reject(Message):
    '''
    See Bluetooth AVDTP spec - 8.13.3 Set Configuration Reject
    '''

    def init_from_payload(self):
        self.acp_seid = self.payload[0] >> 2
        self.error_code = self.payload[1]

    def __init__(self, acp_seid, error_code):
        super().__init__(payload=bytes([acp_seid << 2, error_code]))
        self.acp_seid = acp_seid
        self.error_code = error_code

    def __str__(self):
        details = [
            f'acp_seid:   {self.acp_seid}',
            f'error_code: {name_or_number(AVDTP_ERROR_NAMES, self.error_code)}',
        ]
        return self.to_string(details)


# -----------------------------------------------------------------------------
@Message.subclass
class Close_Command(Simple_Command):
    '''
    See Bluetooth AVDTP spec - 8.14.1 Close Stream Command
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Close_Response(Message):
    '''
    See Bluetooth AVDTP spec - 8.14.2 Close Stream Response
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Close_Reject(Simple_Reject):
    '''
    See Bluetooth AVDTP spec - 8.14.3 Close Stream Reject
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Suspend_Command(Start_Command):
    '''
    See Bluetooth AVDTP spec - 8.15.1 Suspend Command
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Suspend_Response(Message):
    '''
    See Bluetooth AVDTP spec - 8.15.2 Suspend Response
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Suspend_Reject(Start_Reject):
    '''
    See Bluetooth AVDTP spec - 8.15.3 Suspend Reject
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Abort_Command(Simple_Command):
    '''
    See Bluetooth AVDTP spec - 8.16.1 Abort Command
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Abort_Response(Message):
    '''
    See Bluetooth AVDTP spec - 8.16.2 Abort Response
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Security_Control_Command(Message):
    '''
    See Bluetooth AVDTP spec - 8.17.1 Security Control Command
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Security_Control_Response(Message):
    '''
    See Bluetooth AVDTP spec - 8.17.2 Security Control Response
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class Security_Control_Reject(Simple_Reject):
    '''
    See Bluetooth AVDTP spec - 8.17.3 Security Control Reject
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class General_Reject(Message):
    '''
    See Bluetooth AVDTP spec - 8.18 General Reject
    '''

    def to_string(self, details):
        return color('GENERAL_REJECT', 'yellow')


# -----------------------------------------------------------------------------
@Message.subclass
class DelayReport_Command(Message):
    '''
    See Bluetooth AVDTP spec - 8.19.1 Delay Report Command
    '''

    def init_from_payload(self):
        # pylint: disable=attribute-defined-outside-init
        self.acp_seid = self.payload[0] >> 2
        self.delay = (self.payload[1] << 8) | (self.payload[2])

    def __str__(self):
        return self.to_string([f'ACP_SEID: {self.acp_seid}', f'delay:    {self.delay}'])


# -----------------------------------------------------------------------------
@Message.subclass
class DelayReport_Response(Message):
    '''
    See Bluetooth AVDTP spec - 8.19.2 Delay Report Response
    '''


# -----------------------------------------------------------------------------
@Message.subclass
class DelayReport_Reject(Simple_Reject):
    '''
    See Bluetooth AVDTP spec - 8.19.3 Delay Report Reject
    '''


# -----------------------------------------------------------------------------
class Protocol(EventEmitter):
    SINGLE_PACKET = 0
    START_PACKET = 1
    CONTINUE_PACKET = 2
    END_PACKET = 3

    PACKET_TYPE_NAMES = {
        SINGLE_PACKET: 'SINGLE_PACKET',
        START_PACKET: 'START_PACKET',
        CONTINUE_PACKET: 'CONTINUE_PACKET',
        END_PACKET: 'END_PACKET',
    }

    @staticmethod
    def packet_type_name(packet_type):
        return name_or_number(Protocol.PACKET_TYPE_NAMES, packet_type)

    @staticmethod
    async def connect(connection, version=(1, 3)):
        connector = connection.create_l2cap_connector(AVDTP_PSM)
        channel = await connector()
        protocol = Protocol(channel, version)
        protocol.channel_connector = connector

        return protocol

    def __init__(self, l2cap_channel, version=(1, 3)):
        super().__init__()
        self.l2cap_channel = l2cap_channel
        self.version = version
        self.rtx_sig_timer = AVDTP_DEFAULT_RTX_SIG_TIMER
        self.message_assembler = MessageAssembler(self.on_message)
        self.transaction_results = [None] * 16  # Futures for up to 16 transactions
        self.transaction_semaphore = asyncio.Semaphore(16)
        self.transaction_count = 0
        self.channel_acceptor = None
        self.channel_connector = None
        self.local_endpoints = []  # Local endpoints, with contiguous seid values
        self.remote_endpoints = {}  # Remote stream endpoints, by seid
        self.streams = {}  # Streams, by seid

        # Register to receive PDUs from the channel
        l2cap_channel.sink = self.on_pdu
        l2cap_channel.on('open', self.on_l2cap_channel_open)
        l2cap_channel.on('close', self.on_l2cap_channel_close)

    def get_local_endpoint_by_seid(self, seid):
        if 0 < seid <= len(self.local_endpoints):
            return self.local_endpoints[seid - 1]

        return None

    def add_source(self, codec_capabilities, packet_pump):
        seid = len(self.local_endpoints) + 1
        source = LocalSource(self, seid, codec_capabilities, packet_pump)
        self.local_endpoints.append(source)

        return source

    def add_sink(self, codec_capabilities):
        seid = len(self.local_endpoints) + 1
        sink = LocalSink(self, seid, codec_capabilities)
        self.local_endpoints.append(sink)

        return sink

    async def create_stream(self, source, sink):
        # Check that the source isn't already used in a stream
        if source.in_use:
            raise InvalidStateError('source already in use')

        # Create or reuse a new stream to associate the source and the sink
        if source.seid in self.streams:
            stream = self.streams[source.seid]
        else:
            stream = Stream(self, source, sink)
            self.streams[source.seid] = stream

        # The stream can now be configured
        await stream.configure()

        return stream

    async def discover_remote_endpoints(self):
        self.remote_endpoints = {}

        response = await self.send_command(Discover_Command())
        for endpoint_entry in response.endpoints:
            logger.debug(
                f'getting endpoint capabilities for endpoint {endpoint_entry.seid}'
            )
            get_capabilities_response = await self.get_capabilities(endpoint_entry.seid)
            endpoint = DiscoveredStreamEndPoint(
                self,
                endpoint_entry.seid,
                endpoint_entry.media_type,
                endpoint_entry.tsep,
                endpoint_entry.in_use,
                get_capabilities_response.capabilities,
            )
            self.remote_endpoints[endpoint_entry.seid] = endpoint

        return self.remote_endpoints.values()

    def find_remote_sink_by_codec(self, media_type, codec_type):
        for endpoint in self.remote_endpoints.values():
            if (
                not endpoint.in_use
                and endpoint.media_type == media_type
                and endpoint.tsep == AVDTP_TSEP_SNK
            ):
                has_media_transport = False
                has_codec = False
                for capabilities in endpoint.capabilities:
                    if (
                        capabilities.service_category
                        == AVDTP_MEDIA_TRANSPORT_SERVICE_CATEGORY
                    ):
                        has_media_transport = True
                    elif (
                        capabilities.service_category
                        == AVDTP_MEDIA_CODEC_SERVICE_CATEGORY
                    ):
                        if (
                            capabilities.media_type == AVDTP_AUDIO_MEDIA_TYPE
                            and capabilities.media_codec_type == codec_type
                        ):
                            has_codec = True
                if has_media_transport and has_codec:
                    return endpoint

        return None

    def on_pdu(self, pdu):
        self.message_assembler.on_pdu(pdu)

    def on_message(self, transaction_label, message):
        logger.debug(
            f'{color("<<< Received AVDTP message", "magenta")}: '
            f'[{transaction_label}] {message}'
        )

        # Check that the identifier is not reserved
        if message.signal_identifier == 0:
            logger.warning('!!! reserved signal identifier')
            return

        # Check that the identifier is valid
        if (
            message.signal_identifier < 0
            or message.signal_identifier > AVDTP_DELAYREPORT
        ):
            logger.warning('!!! invalid signal identifier')
            self.send_message(transaction_label, General_Reject())

        if message.message_type == Message.COMMAND:
            # Command
            signal_name = (
                AVDTP_SIGNAL_NAMES.get(message.signal_identifier, "")
                .replace("AVDTP_", "")
                .lower()
            )
            handler_name = f'on_{signal_name}_command'
            handler = getattr(self, handler_name, None)
            if handler:
                try:
                    response = handler(message)
                    self.send_message(transaction_label, response)
                except Exception as error:
                    logger.warning(
                        f'{color("!!! Exception in handler:", "red")} {error}'
                    )
            else:
                logger.warning('unhandled command')
        else:
            # Response, look for a pending transaction with the same label
            transaction_result = self.transaction_results[transaction_label]
            if transaction_result is None:
                logger.warning(color('!!! no pending transaction for label', 'red'))
                return

            transaction_result.set_result(message)
            self.transaction_results[transaction_label] = None
            self.transaction_semaphore.release()

    def on_l2cap_connection(self, channel):
        # Forward the channel to the endpoint that's expecting it
        if self.channel_acceptor is None:
            logger.warning(color('!!! l2cap connection with no acceptor', 'red'))
            return
        self.channel_acceptor.on_l2cap_connection(channel)

    def on_l2cap_channel_open(self):
        logger.debug(color('<<< L2CAP channel open', 'magenta'))
        self.emit('open')

    def on_l2cap_channel_close(self):
        logger.debug(color('<<< L2CAP channel close', 'magenta'))
        self.emit('close')

    def send_message(self, transaction_label, message):
        logger.debug(
            f'{color(">>> Sending AVDTP message", "magenta")}: '
            f'[{transaction_label}] {message}'
        )
        max_fragment_size = (
            self.l2cap_channel.mtu - 3
        )  # Enough space for a 3-byte start packet header
        payload = message.payload
        if len(payload) + 2 <= self.l2cap_channel.mtu:
            # Fits in a single packet
            packet_type = self.SINGLE_PACKET
        else:
            packet_type = self.START_PACKET

        done = False
        while not done:
            first_header_byte = (
                transaction_label << 4 | packet_type << 2 | message.message_type
            )

            if packet_type == self.SINGLE_PACKET:
                header = bytes([first_header_byte, message.signal_identifier])
            elif packet_type == self.START_PACKET:
                packet_count = (
                    max_fragment_size - 1 + len(payload)
                ) // max_fragment_size
                header = bytes(
                    [first_header_byte, message.signal_identifier, packet_count]
                )
            else:
                header = bytes([first_header_byte])

            # Send one packet
            self.l2cap_channel.send_pdu(header + payload[:max_fragment_size])

            # Prepare for the next packet
            payload = payload[max_fragment_size:]
            if payload:
                packet_type = (
                    self.CONTINUE_PACKET
                    if payload > max_fragment_size
                    else self.END_PACKET
                )
            else:
                done = True

    async def send_command(self, command):
        # TODO: support timeouts
        # Send the command
        (transaction_label, transaction_result) = await self.start_transaction()
        self.send_message(transaction_label, command)

        # Wait for the response
        response = await transaction_result

        # Check for errors
        if response.message_type in (Message.GENERAL_REJECT, Message.RESPONSE_REJECT):
            raise ProtocolError(response.error_code, 'avdtp')

        return response

    async def start_transaction(self):
        # Wait until we can start a new transaction
        await self.transaction_semaphore.acquire()

        # Look for the next free entry to store the transaction result
        for i in range(16):
            transaction_label = (self.transaction_count + i) % 16
            if self.transaction_results[transaction_label] is None:
                transaction_result = asyncio.get_running_loop().create_future()
                self.transaction_results[transaction_label] = transaction_result
                self.transaction_count += 1
                return (transaction_label, transaction_result)

        assert False  # Should never reach this

    async def get_capabilities(self, seid):
        if self.version > (1, 2):
            return await self.send_command(Get_All_Capabilities_Command(seid))

        return await self.send_command(Get_Capabilities_Command(seid))

    async def set_configuration(self, acp_seid, int_seid, capabilities):
        return await self.send_command(
            Set_Configuration_Command(acp_seid, int_seid, capabilities)
        )

    async def get_configuration(self, seid):
        response = await self.send_command(Get_Configuration_Command(seid))
        return response.capabilities

    async def open(self, seid):
        return await self.send_command(Open_Command(seid))

    async def start(self, seids):
        return await self.send_command(Start_Command(seids))

    async def suspend(self, seids):
        return await self.send_command(Suspend_Command(seids))

    async def close(self, seid):
        return await self.send_command(Close_Command(seid))

    async def abort(self, seid):
        return await self.send_command(Abort_Command(seid))

    def on_discover_command(self, _command):
        endpoint_infos = [
            EndPointInfo(endpoint.seid, 0, endpoint.media_type, endpoint.tsep)
            for endpoint in self.local_endpoints
        ]
        return Discover_Response(endpoint_infos)

    def on_get_capabilities_command(self, command):
        endpoint = self.get_local_endpoint_by_seid(command.acp_seid)
        if endpoint is None:
            return Get_Capabilities_Reject(AVDTP_BAD_ACP_SEID_ERROR)

        return Get_Capabilities_Response(endpoint.capabilities)

    def on_get_all_capabilities_command(self, command):
        endpoint = self.get_local_endpoint_by_seid(command.acp_seid)
        if endpoint is None:
            return Get_All_Capabilities_Reject(AVDTP_BAD_ACP_SEID_ERROR)

        return Get_All_Capabilities_Response(endpoint.capabilities)

    def on_set_configuration_command(self, command):
        endpoint = self.get_local_endpoint_by_seid(command.acp_seid)
        if endpoint is None:
            return Set_Configuration_Reject(AVDTP_BAD_ACP_SEID_ERROR)

        # Check that the local endpoint isn't in use
        if endpoint.in_use:
            return Set_Configuration_Reject(AVDTP_SEP_IN_USE_ERROR)

        # Create a stream object for the pair of endpoints
        stream = Stream(self, endpoint, StreamEndPointProxy(self, command.int_seid))
        self.streams[command.acp_seid] = stream

        result = stream.on_set_configuration_command(command.capabilities)
        return result or Set_Configuration_Response()

    def on_get_configuration_command(self, command):
        endpoint = self.get_local_endpoint_by_seid(command.acp_seid)
        if endpoint is None:
            return Get_Configuration_Reject(AVDTP_BAD_ACP_SEID_ERROR)
        if endpoint.stream is None:
            return Get_Configuration_Reject(AVDTP_BAD_STATE_ERROR)

        return endpoint.stream.on_get_configuration_command()

    def on_reconfigure_command(self, command):
        endpoint = self.get_local_endpoint_by_seid(command.acp_seid)
        if endpoint is None:
            return Reconfigure_Reject(0, AVDTP_BAD_ACP_SEID_ERROR)
        if endpoint.stream is None:
            return Reconfigure_Reject(0, AVDTP_BAD_STATE_ERROR)

        result = endpoint.stream.on_reconfigure_command(command.capabilities)
        return result or Reconfigure_Response()

    def on_open_command(self, command):
        endpoint = self.get_local_endpoint_by_seid(command.acp_seid)
        if endpoint is None:
            return Open_Reject(AVDTP_BAD_ACP_SEID_ERROR)
        if endpoint.stream is None:
            return Open_Reject(AVDTP_BAD_STATE_ERROR)

        result = endpoint.stream.on_open_command()
        return result or Open_Response()

    def on_start_command(self, command):
        for seid in command.acp_seids:
            endpoint = self.get_local_endpoint_by_seid(seid)
            if endpoint is None:
                return Start_Reject(seid, AVDTP_BAD_ACP_SEID_ERROR)
            if endpoint.stream is None:
                return Start_Reject(AVDTP_BAD_STATE_ERROR)

        # Start all streams
        # TODO: deal with partial failures
        for seid in command.acp_seids:
            endpoint = self.get_local_endpoint_by_seid(seid)
            result = endpoint.stream.on_start_command()
            if result is not None:
                return result

        return Start_Response()

    def on_suspend_command(self, command):
        for seid in command.acp_seids:
            endpoint = self.get_local_endpoint_by_seid(seid)
            if endpoint is None:
                return Suspend_Reject(seid, AVDTP_BAD_ACP_SEID_ERROR)
            if endpoint.stream is None:
                return Suspend_Reject(seid, AVDTP_BAD_STATE_ERROR)

        # Suspend all streams
        # TODO: deal with partial failures
        for seid in command.acp_seids:
            endpoint = self.get_local_endpoint_by_seid(seid)
            result = endpoint.stream.on_suspend_command()
            if result is not None:
                return result

        return Suspend_Response()

    def on_close_command(self, command):
        endpoint = self.get_local_endpoint_by_seid(command.acp_seid)
        if endpoint is None:
            return Close_Reject(AVDTP_BAD_ACP_SEID_ERROR)
        if endpoint.stream is None:
            return Close_Reject(AVDTP_BAD_STATE_ERROR)

        result = endpoint.stream.on_close_command()
        return result or Close_Response()

    def on_abort_command(self, command):
        endpoint = self.get_local_endpoint_by_seid(command.acp_seid)
        if endpoint is None or endpoint.stream is None:
            return Abort_Response()

        endpoint.stream.on_abort_command()
        return Abort_Response()

    def on_security_control_command(self, command):
        endpoint = self.get_local_endpoint_by_seid(command.acp_seid)
        if endpoint is None:
            return Security_Control_Reject(AVDTP_BAD_ACP_SEID_ERROR)

        result = endpoint.on_security_control_command(command.payload)
        return result or Security_Control_Response()

    def on_delayreport_command(self, command):
        endpoint = self.get_local_endpoint_by_seid(command.acp_seid)
        if endpoint is None:
            return DelayReport_Reject(AVDTP_BAD_ACP_SEID_ERROR)

        result = endpoint.on_delayreport_command(command.delay)
        return result or DelayReport_Response()


# -----------------------------------------------------------------------------
class Listener(EventEmitter):
    @staticmethod
    def create_registrar(device):
        return device.create_l2cap_registrar(AVDTP_PSM)

    def set_server(self, connection, server):
        self.servers[connection.handle] = server

    def remove_server(self, connection):
        if connection.handle in self.servers:
            del self.servers[connection.handle]

    def __init__(self, registrar, version=(1, 3)):
        super().__init__()
        self.version = version
        self.servers = {}  # Servers, by connection handle

        # Listen for incoming L2CAP connections
        registrar(self.on_l2cap_connection)

    def on_l2cap_connection(self, channel):
        logger.debug(f'{color("<<< incoming L2CAP connection:", "magenta")} {channel}')

        if channel.connection.handle in self.servers:
            # This is a channel for a stream endpoint
            server = self.servers[channel.connection.handle]
            server.on_l2cap_connection(channel)
        else:
            # This is a new command/response channel
            def on_channel_open():
                logger.debug('setting up new Protocol for the connection')
                server = Protocol(channel, self.version)
                self.set_server(channel.connection, server)
                self.emit('connection', server)

            def on_channel_close():
                logger.debug('removing Protocol for the connection')
                self.remove_server(channel.connection)

            channel.on('open', on_channel_open)
            channel.on('close', on_channel_close)


# -----------------------------------------------------------------------------
class Stream:
    '''
    Pair of a local and a remote stream endpoint that can stream from one to the other
    '''

    @staticmethod
    def state_name(state):
        return name_or_number(AVDTP_STATE_NAMES, state)

    def change_state(self, state):
        logger.debug(f'{self} state change -> {color(self.state_name(state), "cyan")}')
        self.state = state

    def send_media_packet(self, packet):
        self.rtp_channel.send_pdu(bytes(packet))

    async def configure(self):
        if self.state != AVDTP_IDLE_STATE:
            raise InvalidStateError('current state is not IDLE')

        await self.remote_endpoint.set_configuration(
            self.local_endpoint.seid, self.local_endpoint.configuration
        )
        self.change_state(AVDTP_CONFIGURED_STATE)

    async def open(self):
        if self.state != AVDTP_CONFIGURED_STATE:
            raise InvalidStateError('current state is not CONFIGURED')

        logger.debug('opening remote endpoint')
        await self.remote_endpoint.open()

        self.change_state(AVDTP_OPEN_STATE)

        # Create a channel for RTP packets
        self.rtp_channel = await self.protocol.channel_connector()

    async def start(self):
        # Auto-open if needed
        if self.state == AVDTP_CONFIGURED_STATE:
            await self.open()

        if self.state != AVDTP_OPEN_STATE:
            raise InvalidStateError('current state is not OPEN')

        logger.debug('starting remote endpoint')
        await self.remote_endpoint.start()

        logger.debug('starting local endpoint')
        await self.local_endpoint.start()

        self.change_state(AVDTP_STREAMING_STATE)

    async def stop(self):
        if self.state != AVDTP_STREAMING_STATE:
            raise InvalidStateError('current state is not STREAMING')

        logger.debug('stopping local endpoint')
        await self.local_endpoint.stop()

        logger.debug('stopping remote endpoint')
        await self.remote_endpoint.stop()

        self.change_state(AVDTP_OPEN_STATE)

    async def close(self):
        if self.state not in (AVDTP_OPEN_STATE, AVDTP_STREAMING_STATE):
            raise InvalidStateError('current state is not OPEN or STREAMING')

        logger.debug('closing local endpoint')
        await self.local_endpoint.close()

        logger.debug('closing remote endpoint')
        await self.remote_endpoint.close()

        # Release any channels we may have created
        self.change_state(AVDTP_CLOSING_STATE)
        if self.rtp_channel:
            await self.rtp_channel.disconnect()
            self.rtp_channel = None

        # Release the endpoint
        self.local_endpoint.in_use = 0

        self.change_state(AVDTP_IDLE_STATE)

    def on_set_configuration_command(self, configuration):
        if self.state != AVDTP_IDLE_STATE:
            return Set_Configuration_Reject(AVDTP_BAD_STATE_ERROR)

        result = self.local_endpoint.on_set_configuration_command(configuration)
        if result is not None:
            return result

        self.change_state(AVDTP_CONFIGURED_STATE)
        return None

    def on_get_configuration_command(self, configuration):
        if self.state not in (
            AVDTP_CONFIGURED_STATE,
            AVDTP_OPEN_STATE,
            AVDTP_STREAMING_STATE,
        ):
            return Get_Configuration_Reject(AVDTP_BAD_STATE_ERROR)

        return self.local_endpoint.on_get_configuration_command(configuration)

    def on_reconfigure_command(self, configuration):
        if self.state != AVDTP_OPEN_STATE:
            return Reconfigure_Reject(AVDTP_BAD_STATE_ERROR)

        result = self.local_endpoint.on_reconfigure_command(configuration)
        if result is not None:
            return result

        return None

    def on_open_command(self):
        if self.state != AVDTP_CONFIGURED_STATE:
            return Open_Reject(AVDTP_BAD_STATE_ERROR)

        result = self.local_endpoint.on_open_command()
        if result is not None:
            return result

        # Register to accept the next channel
        self.protocol.channel_acceptor = self

        self.change_state(AVDTP_OPEN_STATE)
        return None

    def on_start_command(self):
        if self.state != AVDTP_OPEN_STATE:
            return Open_Reject(AVDTP_BAD_STATE_ERROR)

        # Check that we have an RTP channel
        if self.rtp_channel is None:
            logger.warning('received start command before RTP channel establishment')
            return Open_Reject(AVDTP_BAD_STATE_ERROR)

        result = self.local_endpoint.on_start_command()
        if result is not None:
            return result

        self.change_state(AVDTP_STREAMING_STATE)
        return None

    def on_suspend_command(self):
        if self.state != AVDTP_STREAMING_STATE:
            return Open_Reject(AVDTP_BAD_STATE_ERROR)

        result = self.local_endpoint.on_suspend_command()
        if result is not None:
            return result

        self.change_state(AVDTP_OPEN_STATE)
        return None

    def on_close_command(self):
        if self.state not in (AVDTP_OPEN_STATE, AVDTP_STREAMING_STATE):
            return Open_Reject(AVDTP_BAD_STATE_ERROR)

        result = self.local_endpoint.on_close_command()
        if result is not None:
            return result

        self.change_state(AVDTP_CLOSING_STATE)

        if self.rtp_channel is None:
            # No channel to release, we're done
            self.change_state(AVDTP_IDLE_STATE)
        else:
            # TODO: set a timer as we wait for the RTP channel to be closed
            pass

        return None

    def on_abort_command(self):
        if self.rtp_channel is None:
            # No need to wait
            self.change_state(AVDTP_IDLE_STATE)
        else:
            # Wait for the RTP channel to be closed
            self.change_state(AVDTP_ABORTING_STATE)

    def on_l2cap_connection(self, channel):
        logger.debug(color('<<< stream channel connected', 'magenta'))
        self.rtp_channel = channel
        channel.on('open', self.on_l2cap_channel_open)
        channel.on('close', self.on_l2cap_channel_close)

        # We don't need more channels
        self.protocol.channel_acceptor = None

    def on_l2cap_channel_open(self):
        logger.debug(color('<<< stream channel open', 'magenta'))
        self.local_endpoint.on_rtp_channel_open()

    def on_l2cap_channel_close(self):
        logger.debug(color('<<< stream channel closed', 'magenta'))
        self.local_endpoint.on_rtp_channel_close()
        self.local_endpoint.in_use = 0
        self.rtp_channel = None

        if self.state in (AVDTP_CLOSING_STATE, AVDTP_ABORTING_STATE):
            self.change_state(AVDTP_IDLE_STATE)
        else:
            logger.warning('unexpected channel close while not CLOSING or ABORTING')

    def __init__(self, protocol, local_endpoint, remote_endpoint):
        '''
        remote_endpoint must be a subclass of StreamEndPointProxy

        '''
        self.protocol = protocol
        self.local_endpoint = local_endpoint
        self.remote_endpoint = remote_endpoint
        self.rtp_channel = None
        self.state = AVDTP_IDLE_STATE

        local_endpoint.stream = self
        local_endpoint.in_use = 1

    def __str__(self):
        return (
            f'Stream({self.local_endpoint.seid} -> '
            f'{self.remote_endpoint.seid} {self.state_name(self.state)})'
        )


# -----------------------------------------------------------------------------
class StreamEndPoint:
    def __init__(self, seid, media_type, tsep, in_use, capabilities):
        self.seid = seid
        self.media_type = media_type
        self.tsep = tsep
        self.in_use = in_use
        self.capabilities = capabilities

    def __str__(self):
        media_type = f'{name_or_number(AVDTP_MEDIA_TYPE_NAMES, self.media_type)}'
        tsep = f'{name_or_number(AVDTP_TSEP_NAMES, self.tsep)}'
        return '\n'.join(
            [
                'SEP(',
                f'  seid={self.seid}',
                f'  media_type={media_type}',
                f'  tsep={tsep}',
                f'  in_use={self.in_use}',
                '  capabilities=[',
                '\n'.join([f'    {x}' for x in self.capabilities]),
                '  ]',
                ')',
            ]
        )


# -----------------------------------------------------------------------------
class StreamEndPointProxy:
    def __init__(self, protocol, seid):
        self.seid = seid
        self.protocol = protocol

    async def set_configuration(self, int_seid, configuration):
        return await self.protocol.set_configuration(self.seid, int_seid, configuration)

    async def open(self):
        return await self.protocol.open(self.seid)

    async def start(self):
        return await self.protocol.start([self.seid])

    async def stop(self):
        return await self.protocol.suspend([self.seid])

    async def close(self):
        return await self.protocol.close(self.seid)

    async def abort(self):
        return await self.protocol.abort(self.seid)


# -----------------------------------------------------------------------------
class DiscoveredStreamEndPoint(StreamEndPoint, StreamEndPointProxy):
    def __init__(self, protocol, seid, media_type, tsep, in_use, capabilities):
        StreamEndPoint.__init__(self, seid, media_type, tsep, in_use, capabilities)
        StreamEndPointProxy.__init__(self, protocol, seid)


# -----------------------------------------------------------------------------
class LocalStreamEndPoint(StreamEndPoint, EventEmitter):
    def __init__(
        self, protocol, seid, media_type, tsep, capabilities, configuration=None
    ):
        StreamEndPoint.__init__(self, seid, media_type, tsep, 0, capabilities)
        EventEmitter.__init__(self)
        self.protocol = protocol
        self.configuration = configuration if configuration is not None else []
        self.stream = None

    async def start(self):
        pass

    async def stop(self):
        pass

    async def close(self):
        pass

    def on_reconfigure_command(self, command):
        pass

    def on_set_configuration_command(self, configuration):
        logger.debug(
            '<<< received configuration: '
            f'{",".join([str(capability) for capability in configuration])}'
        )
        self.configuration = configuration
        self.emit('configuration')

    def on_get_configuration_command(self):
        return Get_Configuration_Response(self.configuration)

    def on_open_command(self):
        self.emit('open')

    def on_start_command(self):
        self.emit('start')

    def on_suspend_command(self):
        self.emit('suspend')

    def on_close_command(self):
        self.emit('close')

    def on_abort_command(self):
        self.emit('abort')

    def on_rtp_channel_open(self):
        self.emit('rtp_channel_open')

    def on_rtp_channel_close(self):
        self.emit('rtp_channel_close')


# -----------------------------------------------------------------------------
class LocalSource(LocalStreamEndPoint):
    def __init__(self, protocol, seid, codec_capabilities, packet_pump):
        capabilities = [
            ServiceCapabilities(AVDTP_MEDIA_TRANSPORT_SERVICE_CATEGORY),
            codec_capabilities,
        ]
        super().__init__(
            protocol,
            seid,
            codec_capabilities.media_type,
            AVDTP_TSEP_SRC,
            capabilities,
            capabilities,
        )
        self.packet_pump = packet_pump

    async def start(self):
        if self.packet_pump:
            return await self.packet_pump.start(self.stream.rtp_channel)

        self.emit('start')

    async def stop(self):
        if self.packet_pump:
            return await self.packet_pump.stop()

        self.emit('stop')

    def on_start_command(self):
        asyncio.create_task(self.start())

    def on_suspend_command(self):
        asyncio.create_task(self.stop())


# -----------------------------------------------------------------------------
class LocalSink(LocalStreamEndPoint):
    def __init__(self, protocol, seid, codec_capabilities):
        capabilities = [
            ServiceCapabilities(AVDTP_MEDIA_TRANSPORT_SERVICE_CATEGORY),
            codec_capabilities,
        ]
        super().__init__(
            protocol,
            seid,
            codec_capabilities.media_type,
            AVDTP_TSEP_SNK,
            capabilities,
        )

    def on_rtp_channel_open(self):
        logger.debug(color('<<< RTP channel open', 'magenta'))
        self.stream.rtp_channel.sink = self.on_avdtp_packet
        super().on_rtp_channel_open()

    def on_rtp_channel_close(self):
        logger.debug(color('<<< RTP channel close', 'magenta'))
        super().on_rtp_channel_close()

    def on_avdtp_packet(self, packet):
        rtp_packet = MediaPacket.from_bytes(packet)
        logger.debug(
            f'{color("<<< RTP Packet:", "green")} '
            f'{rtp_packet} {rtp_packet.payload[:16].hex()}'
        )
        self.emit('rtp_packet', rtp_packet)