liusuyi
2026-05-06 99ab0d46d30b095d0e1c9d31349f42e0cefc9881
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
package com.ard.zlm.service.impl;
 
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.api.model.v2.ErrorCode;
import com.ard.common.core.constant.Constants;
import com.ard.common.core.constant.SecurityConstants;
import com.ard.common.core.domain.R;
import com.ard.common.core.domain.RtpServerParam;
import com.ard.common.core.enums.LiveStreamType;
import com.ard.common.core.utils.DateUtils;
import com.ard.gb28181.api.RemoteGb28181Service;
import com.ard.gb28181.api.domain.Device;
import com.ard.qs.api.RemoteQsDeviceService;
import com.ard.qs.api.domain.QsDevice;
import com.ard.zlm.api.domain.*;
import com.ard.zlm.api.hook.OriginType;
import com.ard.zlm.common.InviteErrorCode;
import com.ard.zlm.common.InviteSessionStatus;
import com.ard.zlm.common.InviteSessionType;
import com.ard.zlm.config.DynamicTask;
import com.ard.zlm.config.MediaConfig;
import com.ard.zlm.config.UserSetting;
import com.ard.zlm.constants.VideoManagerConstants;
import com.ard.zlm.domain.*;
import com.ard.zlm.domain.dto.ZLMResult;
import com.ard.zlm.event.MediaArrivalEvent;
import com.ard.zlm.event.MediaDepartureEvent;
import com.ard.zlm.hook.Hook;
import com.ard.zlm.hook.HookSubscribe;
import com.ard.zlm.hook.HookType;
import com.ard.zlm.mapper.MediaServerMapper;
import com.ard.zlm.mediaServer.*;
import com.ard.zlm.service.*;
import com.ard.zlm.session.SSRCFactory;
import com.ard.zlm.utils.ZLMRESTfulUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
 
import java.util.*;
 
/**
 * 媒体服务器Service接口实现类
 *
 * @FileName MediaServerServiceImpl
 * @Description
 * @Author fengcheng
 * @date 2026-03-31
 **/
@Slf4j
@Service
public class MediaServerServiceImpl implements IMediaServerService {
 
    @Autowired
    private MediaServerMapper mediaServerMapper;
 
    @Autowired
    private UserSetting userSetting;
 
    @Autowired
    private Map<String, IMediaNodeServerService> nodeServerServiceMap;
 
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Autowired
    private IRedisCatchStorage redisCatchStorage;
 
    @Autowired
    private MediaConfig mediaConfig;
 
    @Autowired
    private IMediaNodeServerService mediaNodeServerService;
 
    @Autowired
    private DynamicTask dynamicTask;
 
    @Autowired
    private HookSubscribe subscribe;
 
    @Autowired
    private RemoteQsDeviceService remoteQsDeviceService;
 
    @Autowired
    private ZLMRESTfulUtils zlmresTfulUtils;
 
    @Autowired
    private SSRCFactory ssrcFactory;
 
    @Autowired
    @Lazy
    private IReceiveRtpServerService receiveRtpServerService;
 
    @Autowired
    @Lazy
    private IInviteStreamService inviteStreamService;
 
    @Autowired
    private IZlmCloudRecordService zlmCloudRecordService;
 
    @Autowired
    private RemoteGb28181Service remoteGb28181Service;
 
 
    @Value("${file.domain}")
    private String fileDomain;
 
    @Value("${file.path}")
    private String filePath;
 
    @Value("${file.prefix}")
    private String filePrefix;
 
 
    /**
     * 流到来的处理
     */
    @Async("taskExecutor")
    @EventListener
    public void onApplicationEvent(MediaArrivalEvent event) {
        if ("rtsp".equals(event.getSchema())) {
            log.info("流变化:注册 app->{}, stream->{}", event.getApp(), event.getStream());
            addCount(event.getMediaServer().getId());
            String type = OriginType.values()[event.getMediaInfo().getOriginType()].getType();
            redisCatchStorage.addStream(event.getMediaServer(), type, event.getApp(), event.getStream(),
                    event.getMediaInfo());
        }
 
        // 推流到来处理
        if ("push".equals(event.getApp())) {
            pushProcessArrival(event);
        }
    }
 
    /**
     * 推流到来处理
     *
     * @param event
     */
    private void pushProcessArrival(MediaArrivalEvent event) {
        MediaInfo mediaInfo = event.getMediaInfo();
        if (mediaInfo == null) {
            return;
        }
        if (mediaInfo.getOriginType() != OriginType.RTMP_PUSH.ordinal() && mediaInfo.getOriginType() != OriginType.RTSP_PUSH.ordinal() && mediaInfo.getOriginType() != OriginType.RTC_PUSH.ordinal()) {
            return;
        }
 
        StreamAuthorityInfo streamAuthorityInfo = redisCatchStorage.getStreamAuthorityInfo(event.getApp(),
                event.getStream());
        if (streamAuthorityInfo == null) {
            streamAuthorityInfo = StreamAuthorityInfo.getInstanceByHook(event);
        } else {
            streamAuthorityInfo.setOriginType(mediaInfo.getOriginType());
        }
        redisCatchStorage.updateStreamAuthorityInfo(event.getApp(), event.getStream(), streamAuthorityInfo);
 
        R<QsDevice> r = remoteQsDeviceService.getQsDeviceStream("pull_" + event.getApp() + "_" + event.getStream(),
                SecurityConstants.INNER);
        if (r.getCode() != Constants.SUCCESS) {
            log.error("获取设备信息失败,stream:{}", event.getStream());
            return;
        }
 
        if (r.getData() == null) {
            r = remoteQsDeviceService.getQsDeviceStream(event.getStream(), SecurityConstants.INNER);
            if (r.getCode() != Constants.SUCCESS) {
                log.error("获取设备信息失败,stream:{}", event.getStream());
                return;
            }
        }
 
        if (r.getData() == null) {
            QsDevice device = new QsDevice();
            device.setDeviceStatus("ON");
            device.setMediaServerId(mediaInfo.getMediaServer().getId());
            device.setDeviceName("推流设备_" + event.getApp() + "_" + event.getStream());
            device.setType(LiveStreamType.PUSH.getCode());
            device.setStatus("ENABLE");
            device.setStreamStatus("1");
            device.setStreamKey(event.getApp() + "_" + event.getStream());
            device.setDeviceCode(event.getStream());
 
            String filePath = snapOnPlay(mediaInfo.getMediaServer(), event.getApp(), event.getStream());
            device.setSnap(filePath);
 
            R<Boolean> addR = remoteQsDeviceService.addQsDevice(device, SecurityConstants.INNER);
            if (addR.getCode() != Constants.SUCCESS) {
                throw new RuntimeException("添加推流设备设备失败" + event.getApp() + "_" + event.getStream());
            }
 
            if (!addR.getData()) {
                throw new RuntimeException("添加推流设备设备失败" + event.getApp() + "_" + event.getStream());
            }
        } else {
            QsDevice device = new QsDevice();
            device.setDeviceStatus("ON");
            device.setMediaServerId(mediaInfo.getMediaServer().getId());
            device.setStreamKey(r.getData().getDeviceCode());
            device.setStreamStatus("1");
            device.setId(r.getData().getId());
            String filePath = snapOnPlay(mediaInfo.getMediaServer(), event.getApp(), event.getStream());
            device.setSnap(filePath);
            R<Boolean> updateR = remoteQsDeviceService.updateQsDevice(device, SecurityConstants.INNER);
            if (updateR.getCode() != Constants.SUCCESS) {
                throw new RuntimeException("修改推流设备设备失败" + event.getApp() + "_" + event.getStream());
            }
 
            if (!updateR.getData()) {
                throw new RuntimeException("修改推流设备设备失败" + event.getApp() + "_" + event.getStream());
            }
        }
 
        // 冗余数据,自己系统中自用
        redisCatchStorage.addPushListItem(event.getApp(), event.getStream(), event.getMediaInfo());
 
    }
 
    /**
     * 流离开的处理
     */
    @Async("taskExecutor")
    @EventListener
    public void onApplicationEvent(MediaDepartureEvent event) {
        if ("rtsp".equals(event.getSchema())) {
            log.info("流变化:注销, app->{}, stream->{}", event.getApp(), event.getStream());
            removeCount(event.getMediaServer().getId());
            MediaInfo mediaInfo = redisCatchStorage.getStreamInfo(event.getApp(), event.getStream(),
                    event.getMediaServer().getId());
            if (mediaInfo == null) {
                return;
            }
            String type = OriginType.values()[mediaInfo.getOriginType()].getType();
            redisCatchStorage.removeStream(mediaInfo.getMediaServer().getId(), type, event.getApp(), event.getStream());
        }
 
        if ("haikang".equals(event.getApp()) || "haikang_isup".equals(event.getApp()) || "dahua".equals(event.getApp()) || "gb28181".equals(event.getApp()) || "jt1078".equals(event.getApp())) {
            InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(null, event.getStream());
            if (inviteInfo != null && (inviteInfo.getType() == InviteSessionType.PLAY || inviteInfo.getType() == InviteSessionType.PLAYBACK)) {
                inviteStreamService.removeInviteInfo(inviteInfo);
 
                R<QsDevice> r = remoteQsDeviceService.getQsDeviceInfo(Long.valueOf(inviteInfo.getDeviceId()),
                        SecurityConstants.INNER);
                if (r.getCode() != Constants.SUCCESS) {
                    return;
                }
 
                if (r.getData() == null) {
                    return;
                }
 
                if ("gb28181".equals(event.getApp())) {
                    // 处理gb28181的停止播放逻辑
                    log.info("[gb28181] 流离开,开始清理资源,stream: {}", event.getStream());
                    R<Device> deviceR = remoteGb28181Service.getDeviceByDeviceId(r.getData().getGbDeviceId(),
                            SecurityConstants.INNER);
                    if (deviceR.getCode() == Constants.SUCCESS && deviceR.getData() != null) {
                        stopGb28181Play(inviteInfo.getType(), r.getData(), deviceR.getData(), event.getStream());
                    }
                } else {
                    // 处理其他类型的停止播放逻辑
                    RTPServerParam rtpServerParam = new RTPServerParam();
                    rtpServerParam.setId(r.getData().getId());
                    rtpServerParam.setType(r.getData().getType());
                    rtpServerParam.setStreamId(event.getStream());
                    stopRtpPlay(rtpServerParam);
 
                    ssrcFactory.releaseSsrc(inviteInfo.getMediaServerId(), null);
                }
            }
        }
 
        if ("video_file".equals(event.getApp())) {
            R<QsDevice> r = remoteQsDeviceService.getQsDeviceStream(event.getStream(), SecurityConstants.INNER);
            if (r.getCode() != Constants.SUCCESS) {
                return;
            }
 
            if (r.getData() == null) {
                return;
            }
 
            QsDevice qsDevice = new QsDevice();
            qsDevice.setId(r.getData().getId());
            qsDevice.setStreamKey("");
            qsDevice.setMediaServerId("");
            qsDevice.setStreamStatus("0");
            R<Boolean> qsDevicer = remoteQsDeviceService.updateQsDevice(qsDevice, SecurityConstants.INNER);
            if (qsDevicer.getCode() != Constants.SUCCESS) {
                log.error("更新设备失败");
            }
        }
 
        // 推流离开处理
        if ("push".equals(event.getApp())) {
            pushProcessLeave(event);
        }
    }
 
    /**
     * 推流离开处理
     *
     * @param event
     */
    private void pushProcessLeave(MediaDepartureEvent event) {
        // 兼容流注销时类型从redis记录获取
        MediaInfo mediaInfo = redisCatchStorage.getPushListItem(event.getApp(), event.getStream());
 
        if (mediaInfo != null) {
            log.info("[推流信息] 查询到redis存在推流缓存, 开始清理,{}/{}", event.getApp(), event.getStream());
            String type = OriginType.values()[mediaInfo.getOriginType()].getType();
            // 冗余数据,自己系统中自用
            redisCatchStorage.removePushListItem(event.getApp(), event.getStream(), event.getMediaServer().getId());
        }
 
        R<QsDevice> r = remoteQsDeviceService.getQsDeviceStream("pull_" + event.getApp() + "_" + event.getStream(),
                SecurityConstants.INNER);
        if (r.getCode() != Constants.SUCCESS) {
            log.error("获取设备信息失败,stream:{}", event.getStream());
            return;
        }
 
        if (r.getData() == null) {
            r = remoteQsDeviceService.getQsDeviceStream(event.getStream(), SecurityConstants.INNER);
            if (r.getCode() != Constants.SUCCESS) {
                log.error("获取设备信息失败,stream:{}", event.getStream());
                return;
            }
        }
 
        if (r.getData() == null) {
            return;
        }
        QsDevice device = new QsDevice();
        device.setDeviceStatus("OFFLINE");
        device.setMediaServerId("");
        device.setStreamKey("");
        device.setStreamStatus("0");
        device.setId(r.getData().getId());
        R<Boolean> updateR = remoteQsDeviceService.updateQsDevice(device, SecurityConstants.INNER);
        if (updateR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("修改推流设备设备失败" + event.getApp() + "_" + event.getStream());
        }
 
        if (!updateR.getData()) {
            throw new RuntimeException("修改推流设备设备失败" + event.getApp() + "_" + event.getStream());
        }
    }
 
    /**
     * 流未找到的处理
     */
    @Async("taskExecutor")
    @EventListener
    public void onApplicationEvent(MediaNotFoundEvent event) {
        log.info("[拉流代理] 自动点播成功,");
    }
 
    /**
     * 流媒体节点上线
     */
    @Async("taskExecutor")
    @EventListener
    @Transactional
    public void onApplicationEvent(MediaServerOnlineEvent event) {
        // 查看是否有未处理的RTP流
        log.info("流媒体节点上线: {}", event.getMediaServer());
        if (event.getMediaServer().getId() == null) {
            return;
        }
 
        String key = VideoManagerConstants.ONLINE_MEDIA_SERVERS_PREFIX + userSetting.getServerId();
        redisTemplate.opsForZSet().incrementScore(key, event.getMediaServer().getId(), 0);
    }
 
    /**
     * 流媒体节点离线
     */
    @Async("taskExecutor")
    @EventListener
    @Transactional
    public void onApplicationEvent(MediaServerOfflineEvent event) {
        log.info("流媒体节点离线: {}", event.getMediaServer());
        if (event.getMediaServer().getId() == null) {
            return;
        }
        String key = VideoManagerConstants.ONLINE_MEDIA_SERVERS_PREFIX + userSetting.getServerId();
        redisTemplate.opsForZSet().remove(key, event.getMediaServer().getId());
    }
 
    /**
     * 流录制完成
     *
     * @param event
     */
    @Async("taskExecutor")
    @EventListener
    public void onApplicationEvent(MediaRecordMp4Event event) {
        CloudRecordItem cloudRecordItem = CloudRecordItem.getInstance(event);
        cloudRecordItem.setServerId(userSetting.getServerId());
        if (ObjectUtils.isEmpty(cloudRecordItem.getCallId())) {
            StreamAuthorityInfo streamAuthorityInfo = redisCatchStorage.getStreamAuthorityInfo(event.getApp(),
                    event.getStream());
            if (streamAuthorityInfo != null) {
                cloudRecordItem.setCallId(streamAuthorityInfo.getCallId());
            }
        }
        log.info("[添加录像记录] {}/{}, callId: {}, 内容:{}", event.getApp(), event.getStream(), cloudRecordItem.getCallId(),
                event.getRecordInfo());
 
        ZlmCloudRecord zlmCloudRecord = new ZlmCloudRecord();
        zlmCloudRecord.setApp(cloudRecordItem.getApp());
        zlmCloudRecord.setStream(cloudRecordItem.getStream());
        zlmCloudRecord.setCallId(cloudRecordItem.getCallId());
        zlmCloudRecord.setServerId(cloudRecordItem.getServerId());
        zlmCloudRecord.setStartTime(cloudRecordItem.getStartTime());
        zlmCloudRecord.setEndTime(cloudRecordItem.getEndTime());
        zlmCloudRecord.setFilePath(cloudRecordItem.getFilePath());
        zlmCloudRecord.setMediaServerId(cloudRecordItem.getMediaServerId());
        zlmCloudRecord.setFileName(cloudRecordItem.getFileName());
        zlmCloudRecord.setFolder(cloudRecordItem.getFolder());
        zlmCloudRecord.setCollect(cloudRecordItem.getCollect());
        zlmCloudRecord.setFileSize(cloudRecordItem.getFileSize());
        zlmCloudRecord.setTimeLen(cloudRecordItem.getTimeLen());
        zlmCloudRecordService.insertZlmCloudRecord(zlmCloudRecord);
    }
 
    public void addCount(String mediaServerId) {
        if (mediaServerId == null) {
            return;
        }
        String key = VideoManagerConstants.ONLINE_MEDIA_SERVERS_PREFIX + userSetting.getServerId();
        redisTemplate.opsForZSet().incrementScore(key, mediaServerId, 1);
 
    }
 
    public void removeCount(String mediaServerId) {
        String key = VideoManagerConstants.ONLINE_MEDIA_SERVERS_PREFIX + userSetting.getServerId();
        redisTemplate.opsForZSet().incrementScore(key, mediaServerId, -1);
    }
 
    /**
     * 获取默认的媒体服务器
     *
     * @return
     */
    @Override
    public ZlmMediaServer getDefaultMediaServer() {
        return mediaServerMapper.queryDefault(userSetting.getServerId());
    }
 
    /**
     * 添加媒体服务器
     *
     * @param zlmMediaServer
     */
    @Override
    public int add(ZlmMediaServer zlmMediaServer) {
        zlmMediaServer.setCreateTime(DateUtils.getNowDate());
        zlmMediaServer.setUpdateTime(DateUtils.getNowDate());
        if (zlmMediaServer.getHookAliveInterval() == null || zlmMediaServer.getHookAliveInterval() == 0F) {
            zlmMediaServer.setHookAliveInterval(10F);
        }
        if (zlmMediaServer.getType() == null) {
            log.info("[添加媒体节点] 失败, mediaServer的类型:为空");
            throw new SecurityException("[添加媒体节点] 失败, mediaServer的类型:为空");
        }
        if (mediaServerMapper.queryOne(zlmMediaServer.getId(), userSetting.getServerId()) != null) {
            log.info("[添加媒体节点] 失败, 媒体服务ID已存在,请修改媒体服务器配置, {}", zlmMediaServer.getId());
            throw new SecurityException("保存失败,媒体服务ID [ " + zlmMediaServer.getId() + " ] 已存在,请修改媒体服务器配置");
        }
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(zlmMediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[添加媒体节点] 失败, mediaServer的类型: {},未找到对应的实现类", zlmMediaServer.getType());
            throw new SecurityException("[添加媒体节点] 失败, mediaServer的类型: " + zlmMediaServer.getType() + ",未找到对应的实现类");
        }
 
        return mediaServerMapper.add(zlmMediaServer);
    }
 
    /**
     * 修改媒体服务器
     *
     * @param zlmMediaServer
     */
    @Override
    public int update(ZlmMediaServer zlmMediaServer) {
        if (!ssrcFactory.hasMediaServerSSRC(zlmMediaServer.getId())) {
            ssrcFactory.initMediaServerSSRC(zlmMediaServer.getId(), null);
        }
        return mediaServerMapper.update(zlmMediaServer);
    }
 
    /**
     * 删除媒体服务器
     *
     * @param zlmMediaServer
     */
    @Override
    public void delete(ZlmMediaServer zlmMediaServer) {
        mediaServerMapper.delOne(zlmMediaServer.getId(), userSetting.getServerId());
 
        // 发送节点移除通知
        MediaServerDeleteEvent event = new MediaServerDeleteEvent(this);
        event.setMediaServer(zlmMediaServer);
        applicationEventPublisher.publishEvent(event);
    }
 
    /**
     * 从数据库中获取所有媒体服务器
     *
     * @return
     */
    @Override
    public List<ZlmMediaServer> getAllFromDatabase() {
        return mediaServerMapper.queryAll(userSetting.getServerId());
    }
 
    /**
     * 从数据库中获取指定id的媒体服务器
     *
     * @param id
     * @return
     */
    @Override
    public ZlmMediaServer getOneFromDatabase(String id) {
        return mediaServerMapper.queryOne(id, userSetting.getServerId());
    }
 
    /**
     * 从数据库中获取指定id的媒体服务器
     *
     * @param id
     * @return
     */
    @Override
    public ZlmMediaServer getOne(String id) {
        return mediaServerMapper.getOne(id);
    }
 
    /**
     * 获取所有在线媒体服务器
     *
     * @return
     */
    @Override
    public List<ZlmMediaServer> getAllOnlineMediaServe() {
        return mediaServerMapper.getAllOnlineMediaServe();
    }
 
    /**
     * 获取负载最小的媒体服务器
     *
     * @param hasAssist 是否包含辅助媒体服务器
     * @return
     */
    @Override
    public ZlmMediaServer getMediaServerForMinimumLoad(Boolean hasAssist) {
        List<ZlmMediaServer> allOnlineMediaServe = getAllOnlineMediaServe();
        if (allOnlineMediaServe.size() == 0) {
            log.info("获取负载最低的节点时无在线节点");
            return null;
        }
 
        String key = VideoManagerConstants.ONLINE_MEDIA_SERVERS_PREFIX + userSetting.getServerId();
 
        // 获取分数最低的,及并发最低的
        Set<Object> objects = redisTemplate.opsForZSet().range(key, 0, -1);
        ArrayList<Object> mediaServerObjectS = new ArrayList<>(objects);
        ZlmMediaServer mediaServer = null;
        if (hasAssist == null) {
            String mediaServerId = (String) mediaServerObjectS.get(0);
            mediaServer = getOne(mediaServerId);
        } else if (hasAssist) {
            for (Object mediaServerObject : mediaServerObjectS) {
                String mediaServerId = (String) mediaServerObject;
                ZlmMediaServer serverItem = getOne(mediaServerId);
                if (serverItem.getRecordAssistPort() > 0) {
                    mediaServer = serverItem;
                    break;
                }
            }
        } else if (!hasAssist) {
            for (Object mediaServerObject : mediaServerObjectS) {
                String mediaServerId = (String) mediaServerObject;
                ZlmMediaServer serverItem = getOne(mediaServerId);
                if (serverItem.getRecordAssistPort() == 0) {
                    mediaServer = serverItem;
                    break;
                }
            }
        }
 
        return mediaServer;
    }
 
    /**
     * 拉流播放
     *
     * @param streamPullPlay 拉流播放请求参数
     * @param callback       回调
     */
    @Override
    public void streamPullPlay(StreamPullPlay streamPullPlay, ErrorCallback<StreamInfo> callback) {
        log.info("[拉流代理] app:{}, stream: {}, 流地址: {}", streamPullPlay.getApp(), streamPullPlay.getStream(),
                streamPullPlay.getUrl());
 
        ZlmMediaServer mediaServer = getMediaServerForMinimumLoad(null);
 
        if (mediaServer == null) {
            callback.run(InviteErrorCode.FAIL.getCode(), "无可用的节点", null);
            return;
        }
        R<QsDevice> devicer = remoteQsDeviceService.getQsDeviceInfo(streamPullPlay.getDeviceId(), SecurityConstants
        .INNER);
        if (devicer.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("获取设备信息失败" + streamPullPlay.getDeviceId());
        }
 
        if (devicer.getData() == null) {
            throw new RuntimeException("设备不存在" + streamPullPlay.getDeviceId());
        }
 
        if ("OFFLINE".equals(devicer.getData().getDeviceStatus())) {
            throw new RuntimeException("设备不在线" + streamPullPlay.getDeviceId());
        }
 
        StreamInfo stream = getStreamInfoByAppAndStreamWithCheck(streamPullPlay.getApp(), streamPullPlay.getStream(),
                mediaServer.getId(), null, false);
        if (stream != null) {
            callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), stream);
            return;
        }
 
        // 设置流超时的定时任务
        String timeOutTaskKey = UUID.randomUUID().toString();
        Hook rtpHook = Hook.getInstance(HookType.on_media_arrival, streamPullPlay.getApp(),
                streamPullPlay.getStream(), mediaServer.getId());
        dynamicTask.startDelay(timeOutTaskKey, () -> {
            log.info("[拉流代理] 收流超时,app:{},stream: {}", streamPullPlay.getApp(), streamPullPlay.getStream());
            // 收流超时
            subscribe.removeSubscribe(rtpHook);
            callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(),
                    InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), null);
        }, userSetting.getPlayTimeout());
 
        // 开启流到来的监听
        subscribe.addSubscribe(rtpHook, (hookData) -> {
            log.info("[拉流代理] 收流成功,app:{},stream: {}", hookData.getApp(), hookData.getStream());
            dynamicTask.stop(timeOutTaskKey);
            StreamInfo streamInfo = getStreamInfoByAppAndStream(mediaServer, hookData.getApp(), hookData.getStream(),
                    hookData.getMediaInfo());
            String filePath = snapOnPlay(streamInfo.getMediaServer(), streamInfo.getApp(), streamInfo.getStream());
            // hook响应
            callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
            subscribe.removeSubscribe(rtpHook);
 
            QsDevice qsDevice = new QsDevice();
            qsDevice.setId(streamPullPlay.getDeviceId());
            qsDevice.setSnap(filePath);
            R<Boolean> r = remoteQsDeviceService.updateQsDevice(qsDevice, SecurityConstants.INNER);
            if (r.getCode() != Constants.SUCCESS) {
                throw new RuntimeException("更新设备失败");
            }
        });
 
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.error("[startProxy] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            callback.run(InviteErrorCode.FAIL.getCode(),
                    "[startProxy] 失败, mediaServer的类型: " + mediaServer.getType() + ",未找到对应的实现类", null);
            return;
        }
 
        String key = mediaNodeServerService.startProxy(mediaServer, streamPullPlay);
        QsDevice qsDevice = new QsDevice();
        qsDevice.setId(streamPullPlay.getDeviceId());
        qsDevice.setStreamKey(key);
        qsDevice.setMediaServerId(mediaServer.getId());
        qsDevice.setStreamStatus("1");
        R<Boolean> r = remoteQsDeviceService.updateQsDevice(qsDevice, SecurityConstants.INNER);
        if (r.getCode() != Constants.SUCCESS) {
            log.error("更新设备失败");
            callback.run(InviteErrorCode.FAIL.getCode(), "更新设备失败", null);
        }
    }
 
    /**
     * 根据应用名和流ID获取播放地址, 通过zlm接口检查是否存在
     *
     * @param app           应用名
     * @param stream        流ID
     * @param mediaServerId 媒体服务器ID
     * @param addr          媒体服务器地址
     * @param authority     鉴权
     * @return
     */
    @Override
    public StreamInfo getStreamInfoByAppAndStreamWithCheck(String app, String stream, String mediaServerId,
                                                           String addr, boolean authority) {
        if (mediaServerId == null) {
            mediaServerId = mediaConfig.getId();
        }
        ZlmMediaServer mediaInfo = getOne(mediaServerId);
        if (mediaInfo == null) {
            throw new RuntimeException("未找到使用的媒体节点");
        }
        List<StreamInfo> streamInfoList = getMediaList(mediaInfo, app, stream);
        if (streamInfoList == null || streamInfoList.isEmpty()) {
            return null;
        } else {
            StreamInfo streamInfo = streamInfoList.get(0);
            if (addr != null && !addr.isEmpty()) {
                streamInfo.changeStreamIp(addr);
            }
            return streamInfo;
        }
    }
 
    /**
     * 根据应用名和流ID获取播放地址, 只是地址拼接
     *
     * @param mediaServer 媒体服务器
     * @param app         应用名
     * @param stream      流ID
     * @param mediaInfo   媒体信息
     * @return
     */
    @Override
    public StreamInfo getStreamInfoByAppAndStream(ZlmMediaServer mediaServer, String app, String stream,
                                                  MediaInfo mediaInfo) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[getStreamInfoByAppAndStream] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            return null;
        }
        return mediaNodeServerService.getStreamInfoByAppAndStream(mediaServer, app, stream, mediaInfo, null, true);
    }
 
    /**
     * 停止拉流播放
     *
     * @param streamPullPlay
     */
    @Override
    public void stopStreamPullPlay(StreamPullPlay streamPullPlay) {
        String mediaServerId = streamPullPlay.getMediaServerId();
        Assert.notNull(mediaServerId, "代理节点不存在");
 
        ZlmMediaServer mediaServer = getOne(mediaServerId);
        if (mediaServer == null) {
            throw new RuntimeException("媒体节点不存在");
        }
 
        stopProxy(mediaServer, streamPullPlay.getStreamKey());
 
        QsDevice qsDevice = new QsDevice();
        qsDevice.setId(streamPullPlay.getDeviceId());
        qsDevice.setStreamKey("");
        qsDevice.setMediaServerId("");
        qsDevice.setStreamStatus("0");
        R<Boolean> r = remoteQsDeviceService.updateQsDevice(qsDevice, SecurityConstants.INNER);
        if (r.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("更新设备失败");
        }
    }
 
    /**
     * 点播成功时调用截图
     *
     * @param mediaServer media
     * @param app         app
     * @param stream      流id
     */
    @Override
    public String snapOnPlay(ZlmMediaServer mediaServer, String app, String stream) {
        String fileName = app + "-" + stream + ".jpg";
        // 请求截图
        log.info("[请求截图]: " + fileName);
 
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[getSnap] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            throw new RuntimeException("[getSnap] 失败, mediaServer的类型: " + mediaServer.getType() + ",未找到对应的实现类");
        }
        String filePath = fileDomain + filePrefix + "/snap/" + fileName;
        mediaNodeServerService.getSnap(mediaServer, app, stream, 15, 1, this.filePath + "/snap", fileName);
        return filePath;
    }
 
    /**
     * 获取截图
     *
     * @param mediaServer
     * @return
     */
    @Override
    public String getSnap(ZlmMediaServer mediaServer, Snap snap) {
        String fileName = snap.getApp() + "-" + snap.getStream() + ".jpg";
        mediaNodeServerService.getSnap(mediaServer, snap.getUrl(), 15, 1, this.filePath + "/snap", fileName);
        return fileDomain + filePrefix + "/snap/" + fileName;
    }
 
    /**
     * 创建RTP服务器
     *
     * @param mediaServer  zlm服务实例
     * @param app          应用名
     * @param streamId     流Id
     * @param ssrc         ssrc
     * @param port         端口, 0/null为使用随机
     * @param onlyAuto     是否只自动分配
     * @param disableAudio 是否禁用音频
     * @param reUsePort    是否重用端口
     * @param tcpMode      0/null udp 模式,1 tcp 被动模式, 2 tcp 主动模式。
     * @return
     */
    @Override
    public int createRTPServer(ZlmMediaServer mediaServer, String app, String streamId, long ssrc, Integer port,
                               Boolean onlyAuto, Boolean disableAudio, Boolean reUsePort, Integer tcpMode) {
        int result = -1;
        // 查询此rtp server 是否已经存在
        ZLMResult<?> rtpInfoResult = zlmresTfulUtils.getRtpInfo(mediaServer, streamId);
        if (rtpInfoResult.getCode() == 0) {
            if (rtpInfoResult.getExist() != null && rtpInfoResult.getExist()) {
                result = rtpInfoResult.getLocal_port();
                if (result == 0) {
                    // 此时说明rtpServer已经创建但是流还没有推上来
                    // 此时重新打开rtpServer
                    Map<String, Object> param = new HashMap<>();
                    param.put("stream_id", streamId);
                    ZLMResult<?> zlmResult = zlmresTfulUtils.closeRtpServer(mediaServer, param);
                    if (zlmResult != null) {
                        if (zlmResult.getCode() == 0) {
                            return createRTPServer(mediaServer, app, streamId, ssrc, port, onlyAuto, disableAudio,
                                    reUsePort, tcpMode);
                        } else {
                            log.warn("[开启rtpServer], 重启RtpServer错误");
                        }
                    }
                }
                return result;
            }
        } else if (rtpInfoResult.getCode() == -2) {
            return result;
        }
 
        Map<String, Object> param = new HashMap<>();
 
        if (tcpMode == null) {
            tcpMode = 0;
        }
        param.put("tcp_mode", tcpMode);
        param.put("app", app);
        param.put("stream_id", streamId);
        if (disableAudio != null) {
            param.put("only_track", disableAudio ? 2 : 0);
        }
 
        if (reUsePort != null) {
            param.put("re_use_port", reUsePort ? "1" : "0");
        }
        // 推流端口设置0则使用随机端口
        if (port == null) {
            param.put("port", 0);
        } else {
            param.put("port", port);
        }
        if (onlyAuto != null) {
            param.put("only_audio", onlyAuto ? "1" : "0");
        }
        if (ssrc != 0) {
            param.put("ssrc", ssrc);
        }
 
        ZLMResult<?> zlmResult = zlmresTfulUtils.openRtpServer(mediaServer, param);
        if (zlmResult != null) {
            if (zlmResult.getCode() == 0) {
                result = zlmResult.getPort();
            } else {
                log.error("创建RTP Server 失败 {}: ", zlmResult.getMsg());
            }
        } else {
            //  检查ZLM状态
            log.error("创建RTP Server 失败 {}: 请检查ZLM服务", param.get("port"));
        }
        return result;
    }
 
    /**
     * rtp播放
     *
     * @param rtpServerParam 创建rtp端口请求参数
     * @return
     */
    @Override
    public void rtpPlay(RTPServerParam rtpServerParam, ErrorCallback<StreamInfo> callback) {
        ZlmMediaServer mediaServer = getMediaServerForMinimumLoad(null);
 
        if (mediaServer == null) {
            callback.run(InviteErrorCode.FAIL.getCode(), "无可用的节点", null);
            return;
        }
 
        R<QsDevice> r = remoteQsDeviceService.getQsDeviceInfo(rtpServerParam.getId(), SecurityConstants.INNER);
        if (r.getCode() != Constants.SUCCESS) {
            callback.run(InviteErrorCode.FAIL.getCode(), "获取设备信息失败" + rtpServerParam.getId(), null);
            return;
        }
        if (r.getData() == null) {
            callback.run(InviteErrorCode.FAIL.getCode(), "设备不存在" + rtpServerParam.getId(), null);
            return;
        }
 
        if ("OFFLINE".equals(r.getData().getDeviceStatus())) {
            callback.run(InviteErrorCode.FAIL.getCode(), "设备不在线" + rtpServerParam.getId(), null);
            return;
        }
 
        int tcpMode = r.getData().getStreamMode().equals("TCP-ACTIVE") ? 2 : (r.getData().getStreamMode().equals("TCP" +
                "-PASSIVE") ? 1 : 0);
        rtpServerParam.setTcpMode(tcpMode);
        rtpServerParam.setMediaServer(mediaServer);
 
        play(mediaServer, rtpServerParam, r.getData(), null, callback);
    }
 
    /**
     * 点播
     *
     * @param mediaServer    zlm服务实例
     * @param rtpServerParam 创建rtp端口请求参数
     * @param device         设备信息
     * @param ssrc           ssrc
     * @param record         是否录制
     * @param callback       回调
     * @return
     */
    private SSRCInfo play(ZlmMediaServer mediaServer, RTPServerParam rtpServerParam, QsDevice device, String ssrc,
                          ErrorCallback<StreamInfo> callback) {
        // 获取点播的状态信息
        InviteInfo inviteInfoInCatch = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY,
                device.getId());
        if (inviteInfoInCatch != null) {
            if (inviteInfoInCatch.getStreamInfo() == null) {
                // 释放生成的ssrc,使用上一次申请的
                ssrcFactory.releaseSsrc(mediaServer.getId(), null);
                // 点播发起了但是尚未成功, 仅注册回调等待结果即可
                inviteStreamService.once(InviteSessionType.PLAY, device.getId(), null, callback);
                log.info("[点播开始] 已经请求中,等待结果, deviceId: {}, channel: {}", device.getId(), device.getId());
                return inviteInfoInCatch.getSsrcInfo();
            } else {
                StreamInfo streamInfo = inviteInfoInCatch.getStreamInfo();
                String streamId = streamInfo.getStream();
                if (streamId == null) {
                    callback.run(InviteErrorCode.ERROR_FOR_CATCH_DATA.getCode(), "点播失败, redis缓存streamId等于null", null);
                    inviteStreamService.call(InviteSessionType.PLAY, device.getId(), null,
                            InviteErrorCode.ERROR_FOR_CATCH_DATA.getCode(), "点播失败, redis缓存streamId等于null", null);
                    return inviteInfoInCatch.getSsrcInfo();
                }
                ZlmMediaServer mediaInfo = streamInfo.getMediaServer();
                Boolean ready = isStreamReady(mediaInfo, rtpServerParam.getApp(), streamId);
                if (ready != null && ready) {
                    if (callback != null) {
                        callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
                    }
                    inviteStreamService.call(InviteSessionType.PLAY, device.getId(), null,
                            InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
                    log.info("[点播已存在] 直接返回, 设备编号: {}", rtpServerParam.getId().intValue());
                    return inviteInfoInCatch.getSsrcInfo();
                } else {
                    // 点播发起了但是尚未成功, 仅注册回调等待结果即可
                    inviteStreamService.once(InviteSessionType.PLAY, device.getId(), null, callback);
                    RTPServerParam rtpServer = new RTPServerParam();
                    rtpServer.setId(rtpServerParam.getId());
                    rtpServer.setType(rtpServerParam.getType());
                    rtpServer.setStreamId(rtpServerParam.getStreamId());
                    stopRtpPlay(rtpServer);
                    inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getId());
                }
            }
        }
 
        rtpServerParam.setMediaServer(mediaServer);
        // 获取mediaServer可用的ssrc
        if (rtpServerParam.getPresetSsrc() != null) {
            ssrc = rtpServerParam.getPresetSsrc();
        } else {
            if (rtpServerParam.isPlayback()) {
                ssrc = ssrcFactory.getPlayBackSsrc(mediaServer.getId());
            } else {
                ssrc = ssrcFactory.getPlaySsrc(mediaServer.getId());
            }
        }
        rtpServerParam.setSsrc(ssrc);
 
        SSRCInfo ssrcInfo = receiveRtpServerService.openRTPServer(rtpServerParam, (code, msg, result) -> {
            if (code == InviteErrorCode.SUCCESS.getCode() && result != null && result.getHookData() != null) {
                log.info("[创建RTP服务器] 成功, code: {}, msg: {}, result: {}", code, msg, result);
                StreamInfo streamInfo = getStreamInfoByAppAndStream(mediaServer, rtpServerParam.getApp(),
                        rtpServerParam.getStreamId(), result.getHookData().getMediaInfo());
                if (streamInfo == null) {
                    if (callback != null) {
                        callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
                                InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
                    }
 
                    inviteStreamService.call(InviteSessionType.PLAY, device.getId(), null,
                            InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
                            InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
                    // 清理资源:关闭RTP服务器并释放SSRC
                    if (result != null && result.getSsrcInfo() != null) {
                        closeRTPServer(mediaServer, result.getSsrcInfo().getStream());
                        ssrcFactory.releaseSsrc(mediaServer.getId(), result.getSsrcInfo().getSsrc());
                    }
                    return;
                }
                if (callback != null) {
                    callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
 
                    inviteStreamService.call(InviteSessionType.PLAY, device.getId(), null,
                            InviteErrorCode.SUCCESS.getCode(),
                            InviteErrorCode.SUCCESS.getMsg(),
                            streamInfo);
 
                    InviteInfo inviteInfo =
                            inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getId());
 
                    if (inviteInfo != null) {
                        inviteInfo.setStatus(InviteSessionStatus.ok);
                        inviteInfo.setStreamInfo(streamInfo);
                        inviteStreamService.updateInviteInfo(inviteInfo);
                    }
 
 
                    String filePath = snapOnPlay(streamInfo.getMediaServer(), streamInfo.getApp(),
                            streamInfo.getStream());
                    QsDevice qsDevice = new QsDevice();
                    qsDevice.setId(rtpServerParam.getId());
                    qsDevice.setStreamKey(rtpServerParam.getStreamId());
                    qsDevice.setMediaServerId(mediaServer.getId());
                    qsDevice.setStreamStatus("1");
                    qsDevice.setSnap(filePath);
                    R<Boolean> r = remoteQsDeviceService.updateQsDevice(qsDevice, SecurityConstants.INNER);
                    if (r.getCode() != Constants.SUCCESS) {
                        throw new RuntimeException("更新设备失败");
                    }
                }
            } else {
                log.error("[创建RTP服务器] 失败, code: {}, msg: {}, result: {}", code, msg, result);
 
                if (callback != null) {
                    callback.run(code, msg, null);
                }
 
                inviteStreamService.call(InviteSessionType.PLAY, device.getId(), null, code, msg, null);
                inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getId());
                // 清理资源:关闭RTP服务器并释放SSRC
                if (result != null && result.getSsrcInfo() != null) {
                    closeRTPServer(mediaServer, result.getSsrcInfo().getStream());
                    ssrcFactory.releaseSsrc(mediaServer.getId(), result.getSsrcInfo().getSsrc());
                }
            }
        });
 
        if (ssrcInfo == null || ssrcInfo.getPort() <= 0) {
            log.info("[点播端口/SSRC]获取失败,设备编号:{}, 通道编号:{},ssrcInfo;{}", device.getId().toString(), device.getId(),
                    ssrcInfo);
            // 释放之前获取的SSRC
            if (rtpServerParam.getPresetSsrc() == null) {
                ssrcFactory.releaseSsrc(mediaServer.getId(), ssrc);
            }
            callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "获取端口或者ssrc失败", null);
            inviteStreamService.call(InviteSessionType.PLAY, device.getId(), null,
                    InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(),
                    InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getMsg(), null);
            return null;
        }
 
        int port = ssrcInfo.getPort();
        String ip = mediaServer.getIp();
        RtpServerParam rtpServer = new RtpServerParam();
        rtpServer.setPort(port);
        rtpServer.setIp(ip);
        rtpServer.setId(rtpServerParam.getId());
        rtpServer.setSsrc(rtpServerParam.getSsrc());
 
        log.info("[点播开始] 设备编号: {}, 通道编号: {}, 收流端口: {}, 流ID:{}, SSRC: {}", device.getId().toString(), device.getId(),
                ssrcInfo.getPort(), ssrcInfo.getStream(), ssrcInfo.getSsrc());
 
        InviteInfo inviteInfo = InviteInfo.getInviteInfo(device.getId().toString(), device.getId(),
                ssrcInfo.getStream(), ssrcInfo, mediaServer.getId(), mediaServer.getSdpIp(), ssrcInfo.getPort(),
                device.getStreamMode(), InviteSessionType.PLAY, InviteSessionStatus.ready, userSetting.getRecordSip());
 
        if ("1".equals(device.getEnableMp4())) {
            inviteInfo.setRecord(true);
        }
 
        inviteStreamService.updateInviteInfo(inviteInfo);
 
        return ssrcInfo;
    }
 
 
    /**
     * 关闭RTP服务器
     *
     * @param mediaServer
     * @param streamId
     */
    @Override
    public void closeRTPServer(ZlmMediaServer mediaServer, String streamId) {
        if (mediaServer == null) {
            return;
        }
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[closeRTPServer] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            return;
        }
        mediaNodeServerService.closeRtpServer(mediaServer, streamId, null);
    }
 
    /**
     * 停止rtp播放
     *
     * @param rtpServerParam 创建rtp端口请求参数
     * @return
     */
    @Override
    public void stopRtpPlay(RTPServerParam rtpServerParam) {
        R<QsDevice> r = remoteQsDeviceService.getQsDeviceInfo(rtpServerParam.getId(), SecurityConstants.INNER);
        if (r.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("获取设备信息失败");
        }
        if (r.getData() == null) {
            throw new RuntimeException("设备不存在");
        }
        QsDevice device = r.getData();
 
        String mediaServerId = device.getMediaServerId();
        ZlmMediaServer mediaServer = getOne(mediaServerId);
        closeRTPServer(mediaServer, device.getStreamKey());
 
        InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, device.getId(),
                rtpServerParam.getStreamId());
 
        if (inviteInfo != null) {
            inviteStreamService.removeInviteInfo(inviteInfo);
 
            if (inviteInfo.getSsrcInfo() != null) {
                ssrcFactory.releaseSsrc(device.getMediaServerId(), inviteInfo.getSsrcInfo().getSsrc());
            }
        }
 
        QsDevice qsDevice = new QsDevice();
        qsDevice.setId(rtpServerParam.getId());
        qsDevice.setStreamKey("");
        qsDevice.setMediaServerId("");
        qsDevice.setStreamStatus("0");
        R<Boolean> devicer = remoteQsDeviceService.updateQsDevice(qsDevice, SecurityConstants.INNER);
        if (devicer.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("更新设备失败");
        }
    }
 
    /**
     * 判断流是否已经准备好
     *
     * @param mediaServer
     * @param app
     * @param streamId
     * @return
     */
    @Override
    public Boolean isStreamReady(ZlmMediaServer mediaServer, String app, String streamId) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[isStreamReady] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            return false;
        }
        MediaInfo mediaInfo = mediaNodeServerService.getMediaInfo(mediaServer, app, streamId);
        return mediaInfo != null;
    }
 
    /**
     * 加载文件形成播放地址
     *
     * @param id       设备id
     * @param callback 回调
     * @return
     */
    @Override
    public void loadRecord(Long id, ErrorCallback<StreamInfo> callback) {
        ZlmMediaServer mediaServer = getMediaServerForMinimumLoad(null);
 
        if (mediaServer == null) {
            callback.run(InviteErrorCode.FAIL.getCode(), "无可用的节点", null);
            return;
        }
 
        R<QsDevice> r = remoteQsDeviceService.getQsDeviceInfo(id, SecurityConstants.INNER);
        if (r.getCode() != Constants.SUCCESS) {
            callback.run(InviteErrorCode.FAIL.getCode(), "获取设备信息失败" + id, null);
            return;
        }
        if (r.getData() == null) {
            callback.run(InviteErrorCode.FAIL.getCode(), "设备不存在" + id, null);
            return;
        }
 
        if ("OFFLINE".equals(r.getData().getDeviceStatus())) {
            throw new RuntimeException("设备不在线" + id);
        }
 
        QsDevice device = r.getData();
        String videoPath = convertUrlToPath(device.getLiveAddress(), this.fileDomain, this.filePrefix, this.filePath);
 
        loadMP4File(mediaServer, "video_file", device.getDeviceCode(), id, videoPath, ((code, msg, streamInfo) -> {
            callback.run(code, msg, streamInfo);
        }));
    }
 
    /**
     * 关闭流文件形成播放地址
     *
     * @param id 设备id
     */
    @Override
    public void closeStreams(Long id) {
        R<QsDevice> r = remoteQsDeviceService.getQsDeviceInfo(id, SecurityConstants.INNER);
        if (r.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("获取设备信息失败");
        }
        if (r.getData() == null) {
            throw new RuntimeException("设备不存在");
        }
 
        QsDevice device = r.getData();
        ZlmMediaServer mediaServer = getOne(device.getMediaServerId());
 
        if (mediaServer == null) {
            throw new RuntimeException("无可用的节点");
        }
 
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[closeStreams] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            return;
        }
        // 停止录像
        mediaNodeServerService.stopRecord(mediaServer, "video_file", device.getStreamKey());
        mediaNodeServerService.closeStreams(mediaServer, "video_file", device.getStreamKey());
 
    }
 
    /**
     * 获取流媒体服务器列表
     *
     * @return
     */
    @Override
    public List<ZlmMediaServer> getAll() {
        return mediaServerMapper.queryAll(userSetting.getServerId());
    }
 
    /**
     * 测试流媒体服务
     *
     * @param ip     流媒体服务IP
     * @param port   流媒体服务HTT端口
     * @param secret 流媒体服务secret
     * @param type   流媒体服务类型
     * @return
     */
    @Override
    public ZlmMediaServer checkMediaServer(String ip, int port, String secret, String type) {
        if (mediaServerMapper.queryOneByHostAndPort(ip, port, userSetting.getServerId()) != null) {
            throw new RuntimeException("此连接已存在");
        }
 
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(type);
        if (mediaNodeServerService == null) {
            log.info("[closeRTPServer] 失败, mediaServer的类型: {},未找到对应的实现类", type);
            return null;
        }
        ZlmMediaServer mediaServer = mediaNodeServerService.checkMediaServer(ip, port, secret);
        if (mediaServer != null) {
            if (mediaServerMapper.queryOne(mediaServer.getId(), userSetting.getServerId()) != null) {
                throw new RuntimeException("媒体服务ID [" + mediaServer.getId() + " ] 已存在,请修改媒体服务器配置");
            }
        }
        return mediaServer;
    }
 
    /**
     * 获取流信息
     *
     * @param app         应用名
     * @param stream      流ID
     * @param mediaServer 媒体服务器
     * @return
     */
    @Override
    public MediaInfo getMediaInfo(ZlmMediaServer mediaServer, String app, String stream) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[getMediaInfo] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            return null;
        }
        return mediaNodeServerService.getMediaInfo(mediaServer, app, stream);
    }
 
    /**
     * 删除录制文件
     *
     * @param mediaServer
     * @param app
     * @param stream
     * @param date
     * @param fileName
     * @return
     */
    @Override
    public boolean deleteRecordDirectory(ZlmMediaServer mediaServer, String app, String stream, String date,
                                         String fileName) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[stopSendRtp] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            return false;
        }
        return mediaNodeServerService.deleteRecordDirectory(mediaServer, app, stream, date, fileName);
    }
 
    /**
     * 获取下载文件路径
     *
     * @param mediaServer
     * @param recordInfo
     * @return
     */
    @Override
    public DownloadFileInfo getDownloadFilePath(ZlmMediaServer mediaServer, RecordInfo recordInfo) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[setRecordSpeed] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            throw new RuntimeException("未找到mediaServer对应的实现类");
        }
        return mediaNodeServerService.getDownloadFilePath(mediaServer, recordInfo);
    }
 
    /**
     * 设置录像播放速度
     *
     * @param mediaServer 使用的节点
     * @param app         应用名
     * @param stream      流id
     * @param stamp       播放速度
     * @param schema      播放协议
     */
    @Override
    public void seekRecordStamp(ZlmMediaServer mediaServer, String app, String stream, Double stamp, String schema) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[seekRecordStamp] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            throw new RuntimeException("未找到mediaServer对应的实现类");
        }
        mediaNodeServerService.seekRecordStamp(mediaServer, app, stream, stamp, schema);
    }
 
    /**
     * 定位录像播放到制定位置
     *
     * @param mediaServer 使用的节点
     * @param app         应用名
     * @param stream      流ID
     * @param speed       要定位的时间位置,从录像开始的时间算起
     * @param schema      播放协议
     */
    @Override
    public void setRecordSpeed(ZlmMediaServer mediaServer, String app, String stream, Integer speed, String schema) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[setRecordSpeed] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            throw new RuntimeException("未找到mediaServer对应的实现类");
        }
        mediaNodeServerService.setRecordSpeed(mediaServer, app, stream, speed, schema);
    }
 
    /**
     * 关闭流
     *
     * @param mediaServer 媒体服务器
     * @param app         应用名
     * @param stream      流ID
     */
    @Override
    public void closeStreams(ZlmMediaServer mediaServer, String app, String stream) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[closeStreams] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            return;
        }
        mediaNodeServerService.closeStreams(mediaServer, app, stream);
    }
 
    /**
     * 开始播放
     *
     * @param device   设备信息
     * @param record   是否录制
     * @param callback 回调
     */
    @Override
    public void play(QsDevice device, Boolean record, ErrorCallback<StreamInfo> callback) {
        ZlmMediaServer mediaServer = getMediaServerForMinimumLoad(null);
 
        if (mediaServer == null) {
            callback.run(InviteErrorCode.FAIL.getCode(), "无可用的节点", null);
            return;
        }
 
        // 播放海康sdk/播放海康isup/播放大华sdk
        if (LiveStreamType.HIK_SDK.getCode().equals(device.getType()) || LiveStreamType.HIK_ISUP.getCode().equals(device.getType()) || LiveStreamType.DAHUA_SDK.getCode().equals(device.getType())) {
            RTPServerParam rtpServerParam = new RTPServerParam();
            if (LiveStreamType.HIK_SDK.getCode().equals(device.getType())) {
                rtpServerParam.setApp("haikang");
            } else if (LiveStreamType.HIK_ISUP.getCode().equals(device.getType())) {
                rtpServerParam.setApp("haikang_isup");
            } else if (LiveStreamType.DAHUA_SDK.getCode().equals(device.getType())) {
                rtpServerParam.setApp("dahua");
            }
 
            rtpServerParam.setStreamId(device.getDeviceCode());
            rtpServerParam.setTcpMode(0);
            rtpServerParam.setType(device.getType());
            rtpServerParam.setId(device.getId());
            System.out.println(rtpServerParam);
            play(mediaServer, rtpServerParam, device, null, callback);
        }
 
        // rtsp/rtmp/flv/hls/onvif
        if (LiveStreamType.RTSP.getCode().equals(device.getType()) || LiveStreamType.RTMP.getCode().equals(device.getType()) || LiveStreamType.FLV.getCode().equals(device.getType()) || LiveStreamType.HLS.getCode().equals(device.getType()) || LiveStreamType.ONVIF.getCode().equals(device.getType())) {
            StreamPullPlay streamPullPlay = new StreamPullPlay();
            streamPullPlay.setDeviceId(device.getId());
            streamPullPlay.setStream(device.getDeviceCode());
            streamPullPlay.setUrl(device.getLiveAddress());
            streamPullPlay.setEnable_mp4("1".equals(device.getEnableMp4()));
            streamPullPlay.setEnable_audio("1".equals(device.getEnableAudio()));
            streamPullPlay.setRtp_type("1");
            streamPullPlay.setTimeOut(10);
 
            if (LiveStreamType.RTSP.getCode().equals(device.getType())) {
                streamPullPlay.setApp("rtsp");
            } else if (LiveStreamType.RTMP.getCode().equals(device.getType())) {
                streamPullPlay.setApp("rtmp");
            } else if (LiveStreamType.FLV.getCode().equals(device.getType())) {
                streamPullPlay.setApp("flv");
                if ("ws".equals(device.getFlvType())) {
                    streamPullPlay.setUrl(convertWsToHttp(device.getLiveAddress()));
                }
            } else if (LiveStreamType.HLS.getCode().equals(device.getType())) {
                streamPullPlay.setApp("hls");
            } else if (LiveStreamType.ONVIF.getCode().equals(device.getType())) {
                streamPullPlay.setApp("onvif");
            }
 
            streamPullPlay(streamPullPlay, callback);
        }
 
        // 视频文件
        if (LiveStreamType.VIDEO_FILE.getCode().equals(device.getType())) {
            loadRecord(device.getId(), callback);
        }
    }
 
    /**
     * 获取流媒体服务器负载
     *
     * @param mediaServer
     * @return
     */
    @Override
    public MediaServerLoad getLoad(ZlmMediaServer mediaServer) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[closeStreams] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            throw new RuntimeException("[closeStreams] 失败, mediaServer的类型: " + mediaServer.getType() + ",未找到对应的实现类");
        }
        ZLMResult<?> threadsLoadZlmResult = mediaNodeServerService.getThreadsLoad(mediaServer);
        ZLMResult<?> workThreadsLoadZlmResult = mediaNodeServerService.getWorkThreadsLoad(mediaServer);
 
        MediaServerLoad result = new MediaServerLoad();
        result.setWorkThreadsLoad(workThreadsLoadZlmResult.getData());
        result.setThreadsLoad(threadsLoadZlmResult.getData());
        result.setId(mediaServer.getId());
        return result;
    }
 
    /**
     * 重启流媒体
     *
     * @param mediaServer 流媒体
     * @return
     */
    @Override
    public void restartServer(ZlmMediaServer mediaServer) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[closeStreams] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            return;
        }
        mediaNodeServerService.restartServer(mediaServer);
    }
 
    /**
     * 生成推流地址
     *
     * @param id     设备id
     * @param callId
     * @return
     */
    @Override
    public Map<String, Object> getStreamPushAddress(Long id, String callId) {
        R<QsDevice> r = remoteQsDeviceService.getQsDeviceInfo(id, SecurityConstants.INNER);
        if (r.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("获取设备信息失败");
        }
        if (r.getData() == null) {
            throw new RuntimeException("设备不存在");
        }
        ZlmMediaServer mediaServer = getMediaServerForMinimumLoad(null);
        String sign = DigestUtils.md5DigestAsHex((callId + '_' + userSetting.getPushKey()).getBytes());
 
        HashMap<String, Object> map = new HashMap<>();
 
        String rtsp = StrUtil.format("rtsp://{}:{}/push/{}?callId={}&sign={}", mediaServer.getIp(),
                mediaServer.getRtspPort(), r.getData().getDeviceCode(), callId, sign);
 
        String rtmp = StrUtil.format("rtmp://{}:{}/push/{}?callId={}&sign={}", mediaServer.getIp(),
                mediaServer.getRtmpPort(), r.getData().getDeviceCode(), callId, sign);
        map.put("rtsp", rtsp);
        map.put("rtmp", rtmp);
        return map;
    }
 
    /**
     * 推流播放
     *
     * @param id
     * @param callback
     */
    @Override
    public void streamPullPush(Long id, ErrorCallback<StreamInfo> callback) {
        R<QsDevice> r = remoteQsDeviceService.getQsDeviceInfo(id, SecurityConstants.INNER);
        if (r.getCode() != Constants.SUCCESS) {
            log.info("获取设备信息失败 id:{}", id);
            callback.run(InviteErrorCode.FAIL.getCode(), "获取设备信息失败", null);
            return;
        }
        if (r.getData() == null) {
            log.info("设备不存在 id:{}", id);
            callback.run(InviteErrorCode.FAIL.getCode(), "设备不存在", null);
            return;
        }
        QsDevice device = r.getData();
 
        if (!LiveStreamType.PUSH.getCode().equals(device.getType())) {
            log.info("直播流接入类型不对,应当是PUSH id:{}", id);
            callback.run(InviteErrorCode.FAIL.getCode(), "直播流接入类型不对,应当是PUSH", null);
            return;
        }
 
        ZlmMediaServer mediaServer = getOne(device.getMediaServerId());
        if (mediaServer != null) {
            MediaInfo mediaInfo = getMediaInfo(mediaServer, "push", device.getDeviceCode());
            if (mediaInfo != null) {
                String callId = null;
                StreamAuthorityInfo streamAuthorityInfo = redisCatchStorage.getStreamAuthorityInfo("push",
                        device.getDeviceCode());
                if (streamAuthorityInfo != null) {
                    callId = streamAuthorityInfo.getCallId();
                }
                callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(),
                        getStreamInfoByAppAndStream(mediaServer, "push", device.getDeviceCode(), mediaInfo));
                if ("0".equals(device.getStreamStatus())) {
                    QsDevice qsDevice = new QsDevice();
                    qsDevice.setId(id);
                    qsDevice.setStreamStatus("1");
                    R<Boolean> updateR = remoteQsDeviceService.updateQsDevice(qsDevice, SecurityConstants.INNER);
                    if (updateR.getCode() != Constants.SUCCESS) {
                        log.info("修改推流设备设备失败 id:{}", id);
                        throw new RuntimeException("修改推流设备设备失败");
                    }
 
                    if (!updateR.getData()) {
                        log.info("修改推流设备设备失败 id:{}", id);
                        throw new RuntimeException("修改推流设备设备失败");
                    }
                }
                return;
            }
        }
    }
 
    /**
     * gb28181 播放
     *
     * @param qsDevice
     * @param gbDevice
     * @param callback
     */
    @Override
    public void startGb28181Play(QsDevice qsDevice, Device gbDevice, ErrorCallback<StreamInfo> callback) {
        ZlmMediaServer mediaServer = getMediaServerForMinimumLoad(null);
 
        if (mediaServer == null) {
            callback.run(InviteErrorCode.FAIL.getCode(), "无可用的节点", null);
            return;
        }
 
        int tcpMode = qsDevice.getStreamMode().equals("TCP-ACTIVE") ? 2 : (qsDevice.getStreamMode().equals("TCP" +
                "-PASSIVE") ? 1 : 0);
 
        RTPServerParam rtpServerParam = new RTPServerParam();
        rtpServerParam.setApp("gb28181");
        rtpServerParam.setMediaServer(mediaServer);
        rtpServerParam.setType(LiveStreamType.GB28181.getCode());
        rtpServerParam.setStreamId(qsDevice.getDeviceCode());
        rtpServerParam.setTcpMode(tcpMode);
        rtpServerParam.setId(qsDevice.getId());
 
        startGb28181PlayFun(mediaServer, qsDevice, gbDevice, rtpServerParam, null, callback);
    }
 
    /**
     * 连接rtp服务
     *
     * @param mediaServer
     * @param address
     * @param port
     * @param stream
     * @return
     */
    @Override
    public Boolean connectRtpServer(ZlmMediaServer mediaServer, String address, int port, String stream) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[connectRtpServer] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            return false;
        }
        return mediaNodeServerService.connectRtpServer(mediaServer, address, port, stream);
    }
 
    /**
     * gb28181 停止点播
     *
     * @param type
     * @param qsDevice
     * @param device
     * @param stream
     */
    @Override
    public void stopGb28181Play(InviteSessionType type, QsDevice qsDevice, Device device, String stream) {
        InviteInfo inviteInfo = inviteStreamService.getInviteInfo(type, qsDevice.getId(), stream);
        if (inviteInfo == null) {
            if (type == InviteSessionType.PLAY) {
                QsDevice qsDeviceUpdate = new QsDevice();
                qsDeviceUpdate.setId(qsDevice.getId());
                qsDeviceUpdate.setStreamKey("");
                qsDeviceUpdate.setMediaServerId("");
                qsDeviceUpdate.setStreamStatus("0");
                R<Boolean> r = remoteQsDeviceService.updateQsDevice(qsDeviceUpdate, SecurityConstants.INNER);
                if (r.getCode() != Constants.SUCCESS) {
                    throw new RuntimeException("更新设备失败");
                }
            }
            return;
        }
        inviteStreamService.removeInviteInfo(inviteInfo);
        if (InviteSessionStatus.ok == inviteInfo.getStatus()) {
            try {
                log.info("[停止点播/回放/下载] {}/{}", qsDevice.getGbDeviceId(), qsDevice.getGbChannelId());
 
                RtpServerParam rtpServer = new RtpServerParam();
                rtpServer.setApp("gb28181");
                rtpServer.setStream(qsDevice.getDeviceCode());
                rtpServer.setGbDeviceId(qsDevice.getGbDeviceId());
                rtpServer.setGbChannelId(qsDevice.getGbChannelId());
 
                R<Void> r = remoteGb28181Service.streamByeCmd(rtpServer, SecurityConstants.INNER);
                if (r.getCode() != Constants.SUCCESS) {
                    log.error("[命令发送失败] 停止点播/回放/下载, deviceId:{}", qsDevice.getGbDeviceId());
                    throw new RuntimeException("[命令发送失败] 停止点播/回放/下载, deviceId:" + qsDevice.getGbDeviceId());
                }
            } catch (Exception e) {
                log.error("[命令发送失败] 停止点播/回放/下载, 发送BYE: {}", e.getMessage());
                throw new RuntimeException("命令发送失败: " + e.getMessage());
            }
        }
 
        if (inviteInfo.getType() == InviteSessionType.PLAY) {
            QsDevice qsDeviceUpdate = new QsDevice();
            qsDeviceUpdate.setId(qsDevice.getId());
            qsDeviceUpdate.setStreamKey("");
            qsDeviceUpdate.setMediaServerId("");
            qsDeviceUpdate.setStreamStatus("0");
            R<Boolean> r = remoteQsDeviceService.updateQsDevice(qsDeviceUpdate, SecurityConstants.INNER);
            if (r.getCode() != Constants.SUCCESS) {
                throw new RuntimeException("更新设备失败");
            }
        }
 
        ZlmMediaServer mediaServer = null;
        if (inviteInfo.getStreamInfo() != null) {
            mediaServer = inviteInfo.getStreamInfo().getMediaServer();
        } else {
            mediaServer = getOne(inviteInfo.getMediaServerId());
        }
 
        if (mediaServer != null && inviteInfo.getSsrcInfo() != null) {
            closeRTPServer(mediaServer, inviteInfo.getSsrcInfo().getStream());
            ssrcFactory.releaseSsrc(inviteInfo.getMediaServerId(), inviteInfo.getSsrcInfo().getSsrc());
        }
    }
 
 
    /**
     * 开启国标28181播放
     *
     * @param mediaServer
     * @param device
     * @param rtpServerParam
     * @param ssrc
     * @param callback
     */
    private SSRCInfo startGb28181PlayFun(ZlmMediaServer mediaServer, QsDevice device, Device gbDevice,
                                         RTPServerParam rtpServerParam, String ssrc,
                                         ErrorCallback<StreamInfo> callback) {
        // 获取点播的状态信息
        InviteInfo inviteInfoInCatch = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY,
                device.getId());
        if (inviteInfoInCatch != null) {
            if (inviteInfoInCatch.getStreamInfo() == null) {
                // 释放生成的ssrc,使用上一次申请的
                ssrcFactory.releaseSsrc(mediaServer.getId(), null);
                // 点播发起了但是尚未成功, 仅注册回调等待结果即可
                inviteStreamService.once(InviteSessionType.PLAY, device.getId(), null, callback);
                log.info("[点播开始] 已经请求中,等待结果, deviceId: {}, channel: {}", device.getId(), device.getId());
                return inviteInfoInCatch.getSsrcInfo();
            } else {
                StreamInfo streamInfo = inviteInfoInCatch.getStreamInfo();
                String streamId = streamInfo.getStream();
                if (streamId == null) {
                    callback.run(InviteErrorCode.ERROR_FOR_CATCH_DATA.getCode(), "点播失败, redis缓存streamId等于null", null);
                    inviteStreamService.call(InviteSessionType.PLAY, device.getId(), null,
                            InviteErrorCode.ERROR_FOR_CATCH_DATA.getCode(), "点播失败, redis缓存streamId等于null", null);
                    return inviteInfoInCatch.getSsrcInfo();
                }
                ZlmMediaServer mediaInfo = streamInfo.getMediaServer();
                Boolean ready = isStreamReady(mediaInfo, rtpServerParam.getApp(), streamId);
                if (ready != null && ready) {
                    if (callback != null) {
                        callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
                    }
                    inviteStreamService.call(InviteSessionType.PLAY, device.getId(), null,
                            InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
                    log.info("[点播已存在] 直接返回, 设备编号: {}", device.getId());
                    return inviteInfoInCatch.getSsrcInfo();
                } else {
                    // 点播发起了但是尚未成功, 仅注册回调等待结果即可
                    inviteStreamService.once(InviteSessionType.PLAY, device.getId(), null, callback);
                    RTPServerParam rtpServer = new RTPServerParam();
                    rtpServer.setId(device.getId());
                    rtpServer.setType(rtpServerParam.getType());
                    rtpServer.setStreamId(rtpServerParam.getStreamId());
                    stopRtpPlay(rtpServer);
                    inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getId());
                }
            }
        }
 
        rtpServerParam.setMediaServer(mediaServer);
        // 获取mediaServer可用的ssrc
        if (rtpServerParam.getPresetSsrc() != null) {
            ssrc = rtpServerParam.getPresetSsrc();
        } else {
            if (rtpServerParam.isPlayback()) {
                ssrc = ssrcFactory.getPlayBackSsrc(mediaServer.getId());
            } else {
                ssrc = ssrcFactory.getPlaySsrc(mediaServer.getId());
            }
        }
        rtpServerParam.setSsrc(ssrc);
 
        SSRCInfo ssrcInfo = receiveRtpServerService.openRTPServer(rtpServerParam, (code, msg, result) -> {
            if (code == InviteErrorCode.SUCCESS.getCode() && result != null && result.getHookData() != null) {
                log.info("[创建RTP服务器] 成功, code: {}, msg: {}, result: {}", code, msg, result);
                StreamInfo streamInfo = getStreamInfoByAppAndStream(mediaServer, rtpServerParam.getApp(),
                        rtpServerParam.getStreamId(), result.getHookData().getMediaInfo());
                if (streamInfo == null) {
                    if (callback != null) {
                        callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
                                InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
                    }
 
                    inviteStreamService.call(InviteSessionType.PLAY, device.getId(), null,
                            InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
                            InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
                    // 清理资源:关闭RTP服务器并释放SSRC
                    if (result != null && result.getSsrcInfo() != null) {
                        closeRTPServer(mediaServer, result.getSsrcInfo().getStream());
                        ssrcFactory.releaseSsrc(mediaServer.getId(), result.getSsrcInfo().getSsrc());
                    }
                    return;
                }
                if (callback != null) {
                    callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
 
                    inviteStreamService.call(InviteSessionType.PLAY, device.getId(), null,
                            InviteErrorCode.SUCCESS.getCode(),
                            InviteErrorCode.SUCCESS.getMsg(),
                            streamInfo);
 
                    InviteInfo inviteInfo =
                            inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getId());
 
                    if (inviteInfo != null) {
                        inviteInfo.setStatus(InviteSessionStatus.ok);
                        inviteInfo.setStreamInfo(streamInfo);
                        inviteStreamService.updateInviteInfo(inviteInfo);
                    }
 
 
                    String filePath = snapOnPlay(streamInfo.getMediaServer(), streamInfo.getApp(),
                            streamInfo.getStream());
                    QsDevice qsDevice = new QsDevice();
                    qsDevice.setId(rtpServerParam.getId());
                    qsDevice.setStreamKey(rtpServerParam.getStreamId());
                    qsDevice.setMediaServerId(mediaServer.getId());
                    qsDevice.setStreamStatus("1");
                    qsDevice.setSnap(filePath);
                    R<Boolean> r = remoteQsDeviceService.updateQsDevice(qsDevice, SecurityConstants.INNER);
                    if (r.getCode() != Constants.SUCCESS) {
                        throw new RuntimeException("更新设备失败");
                    }
                }
            } else {
                log.error("[创建RTP服务器] 失败, code: {}, msg: {}, result: {}", code, msg, result);
 
                if (callback != null) {
                    callback.run(code, msg, null);
                }
 
                inviteStreamService.call(InviteSessionType.PLAY, device.getId(), null, code, msg, null);
                inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getId());
                // 清理资源:关闭RTP服务器并释放SSRC
                if (result != null && result.getSsrcInfo() != null) {
                    closeRTPServer(mediaServer, result.getSsrcInfo().getStream());
                    ssrcFactory.releaseSsrc(mediaServer.getId(), result.getSsrcInfo().getSsrc());
                }
            }
        });
 
        if (ssrcInfo == null || ssrcInfo.getPort() <= 0) {
            log.info("[点播端口/SSRC]获取失败,设备编号:{}, 通道编号:{},ssrcInfo;{}", device.getId().toString(), device.getId(),
                    ssrcInfo);
            // 释放之前获取的SSRC
            if (rtpServerParam.getPresetSsrc() == null) {
                ssrcFactory.releaseSsrc(mediaServer.getId(), ssrc);
            }
            callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "获取端口或者ssrc失败", null);
            inviteStreamService.call(InviteSessionType.PLAY, device.getId(), null,
                    InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(),
                    InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getMsg(), null);
            return null;
        }
 
        int port = ssrcInfo.getPort();
        String ip = mediaServer.getIp();
        RtpServerParam rtpServer = new RtpServerParam();
        rtpServer.setPort(port);
        rtpServer.setIp(ip);
        rtpServer.setId(rtpServerParam.getId());
        rtpServer.setSsrc(rtpServerParam.getSsrc());
        rtpServer.setGbDeviceId(gbDevice.getDeviceId());
        rtpServer.setGbChannelId(device.getGbChannelId());
        rtpServer.setStreamMode(gbDevice.getStreamMode());
        rtpServer.setMediaServerId(mediaServer.getId());
        rtpServer.setApp(rtpServerParam.getApp());
        rtpServer.setStream(rtpServerParam.getStreamId());
 
        log.info("[国标28181点播开始] ===============================");
        log.info("[国标28181] 设备ID: {}, 设备国标ID: {}, 通道国标ID: {}", device.getId(), gbDevice.getDeviceId(),
                device.getGbChannelId());
        log.info("[国标28181] 流模式: {}, ZLM tcpMode: {}, ssrcCheck: {}", gbDevice.getStreamMode(),
                rtpServerParam.getTcpMode(), rtpServerParam.isSsrcCheck());
        log.info("[国标28181] ZLM媒体服务器IP: {}, 收流端口: {}, 流ID: {}, SSRC: {}", ip, port, ssrcInfo.getStream(),
                ssrcInfo.getSsrc());
        log.info("[国标28181] =======================================");
 
        InviteInfo inviteInfo = InviteInfo.getInviteInfo(device.getId().toString(), device.getId(),
                ssrcInfo.getStream(), ssrcInfo, mediaServer.getId(), mediaServer.getSdpIp(), ssrcInfo.getPort(),
                gbDevice.getStreamMode(), InviteSessionType.PLAY, InviteSessionStatus.ready,
                userSetting.getRecordSip());
 
        if ("1".equals(device.getEnableMp4())) {
            inviteInfo.setRecord(true);
        }
 
        inviteStreamService.updateInviteInfo(inviteInfo);
 
        R<Void> r = remoteGb28181Service.playStreamCmd(rtpServer, SecurityConstants.INNER);
 
        if (r.getCode() != Constants.SUCCESS) {
            log.info("[点播失败]{}:{} deviceId: {}, channelId:{}", r.getCode(), r.getMsg(), device.getGbDeviceId(),
                    device.getGbChannelId());
            inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, device.getId(),
                    rtpServerParam.getStreamId());
 
            if (inviteInfo != null) {
                inviteStreamService.removeInviteInfo(inviteInfo);
                if (inviteInfo.getSsrcInfo() != null) {
                    ssrcFactory.releaseSsrc(mediaServer.getId(), inviteInfo.getSsrcInfo().getSsrc());
                }
            }
 
            closeRTPServer(mediaServer, ssrcInfo.getStream());
            ssrcFactory.releaseSsrc(mediaServer.getId(), ssrcInfo.getSsrc());
 
 
            if (callback != null) {
                callback.run(r.getCode(), r.getMsg(), null);
            }
            inviteStreamService.call(InviteSessionType.PLAY, device.getId(), null,
                    r.getCode(), r.getMsg(), null);
 
            inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getId());
            return ssrcInfo;
        }
        return ssrcInfo;
    }
 
    /**
     * 将 WebSocket 协议地址转换为 HTTP 协议地址
     * ws:// -> http://
     * wss:// -> https://
     *
     * @param wsUrl 输入的 WebSocket 地址
     * @return 转换后的 HTTP 地址
     */
    public static String convertWsToHttp(String wsUrl) {
        // 1. 空值检查
        if (wsUrl == null || wsUrl.isEmpty()) {
            return wsUrl;
        }
 
        // 2. 判断并替换协议
        if (wsUrl.startsWith("wss://")) {
            return wsUrl.replace("wss://", "https://");
        } else if (wsUrl.startsWith("ws://")) {
            return wsUrl.replace("ws://", "http://");
        }
 
        // 3. 如果已经是 http/https 或其他格式,直接返回
        return wsUrl;
    }
 
    private void loadMP4File(ZlmMediaServer mediaServer, String app, String stream, Long id, String videoPath,
                             ErrorCallback<StreamInfo> callback) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[loadMP4File] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            throw new RuntimeException("未找到mediaServer对应的实现类");
        }
 
        StreamInfo streamData = getStreamInfoByAppAndStreamWithCheck(app, stream, mediaServer.getId(), null, false);
        if (streamData != null) {
            callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamData);
            return;
        }
 
        Hook hook = Hook.getInstance(HookType.on_media_arrival, app, stream, mediaServer.getServerId());
        subscribe.addSubscribe(hook, (hookData) -> {
            StreamInfo streamInfo = getStreamInfoByAppAndStream(mediaServer, app, stream, hookData.getMediaInfo());
            if (callback != null) {
                callback.run(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg(), streamInfo);
 
                QsDevice qsDevice = new QsDevice();
                qsDevice.setId(id);
                qsDevice.setStreamKey(stream);
                qsDevice.setMediaServerId(mediaServer.getId());
                qsDevice.setStreamStatus("1");
                R<Boolean> r = remoteQsDeviceService.updateQsDevice(qsDevice, SecurityConstants.INNER);
                if (r.getCode() != Constants.SUCCESS) {
                    log.error("更新设备失败");
                    callback.run(InviteErrorCode.FAIL.getCode(), "更新设备失败", null);
                }
 
                // 开启录像
                mediaNodeServerService.startRecord(mediaServer, app, stream);
            }
        });
 
        ZLMResult<?> zlmResult = zlmresTfulUtils.loadMP4File(mediaServer, app, stream, videoPath);
 
        if (zlmResult == null) {
            throw new RuntimeException("请求失败");
        }
        if (zlmResult.getCode() != 0) {
            throw new RuntimeException(zlmResult.getMsg());
        }
    }
 
    private void stopProxy(ZlmMediaServer mediaServer, String streamKey) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[stopProxy] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            throw new RuntimeException("未找到mediaServer对应的实现类");
        }
        mediaNodeServerService.stopProxy(mediaServer, streamKey);
    }
 
    public List<StreamInfo> getMediaList(ZlmMediaServer mediaServer, String app, String stream) {
        IMediaNodeServerService mediaNodeServerService = nodeServerServiceMap.get(mediaServer.getType());
        if (mediaNodeServerService == null) {
            log.info("[getMediaList] 失败, mediaServer的类型: {},未找到对应的实现类", mediaServer.getType());
            return new ArrayList<>();
        }
        return mediaNodeServerService.getMediaList(mediaServer, app, stream);
    }
 
 
    /**
     * 将网络访问路径转换为本地文件物理路径
     */
    public String convertUrlToPath(String url, String domain, String prefix, String localBasePath) {
        // 步骤 A: 去除域名部分
        // 例如:http://127.0.0.1:9300/statics/...  ->  /statics/...
        if (url.startsWith(domain)) {
            url = url.substring(domain.length());
        }
 
        // 步骤 B: 去除前缀部分
        // 例如:/statics/2026/...  ->  /2026/...
        if (url.startsWith(prefix)) {
            url = url.substring(prefix.length());
        }
 
        // 步骤 C: 拼接本地路径
        // 注意:防止路径分隔符重复或缺失
        // localBasePath: D:/ruoyi/uploadPath
        // url: /2026/03/27/...
 
        if (url.startsWith("/")) {
            return localBasePath + url;
        } else {
            return localBasePath + "/" + url;
        }
    }
}