liusuyi
2026-06-02 f652169cc5d6501511eece5df57b7b396fd7a7ab
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
package com.ard.zlm.controller;
 
import com.alibaba.fastjson2.JSONObject;
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.enums.LiveStreamType;
import com.ard.common.core.utils.StringUtils;
import com.ard.common.core.web.domain.AjaxResult;
import com.ard.gb28181.api.RemoteGb28181Service;
import com.ard.gb28181.api.domain.Device;
import com.ard.gb28181.api.domain.DeviceChannel;
import com.ard.gb28181.api.domain.GbChannelDTO;
import com.ard.zlm.domain.StreamChannel;
import com.ard.zlm.service.ZlmStreamService;
import com.ard.work.api.RemoteCameraService;
import com.ard.zlm.api.domain.*;
import com.ard.zlm.common.InviteErrorCode;
import com.ard.zlm.common.InviteSessionType;
import com.ard.zlm.config.UserSetting;
import com.ard.zlm.domain.Snap;
import com.ard.zlm.mediaServer.MediaServerChangeEvent;
import com.ard.zlm.service.ErrorCallback;
import com.ard.zlm.service.IInviteStreamService;
import com.ard.zlm.service.IMediaServerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;
 
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
 
/**
 * zlm 接口
 *
 * @FileName ZlmController
 * @Description
 * @Author fengcheng
 * @date 2026-04-01
 **/
@Tag(name = "zlm接口")
@Slf4j
@RestController
public class ZlmController {
 
    @Resource
    private IMediaServerService mediaServerService;
 
    @Resource
    private UserSetting userSetting;
 
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;
 
    @Resource
    private RemoteGb28181Service remoteGb28181Service;
 
    @Resource
    private ZlmStreamService zlmStreamService;
 
    @Resource
    @Lazy
    private IInviteStreamService inviteStreamService;
 
    /**
     * 拉流播放
     *
     * @param streamPullPlay 拉流播放请求参数
     * @param request        HttpServletRequest
     * @return
     */
    @Operation(summary = "拉流播放代理")
    @PostMapping("/streamPullPlay")
    public DeferredResult<R<StreamContent>> streamPullPlay(@RequestBody StreamPullPlay streamPullPlay, HttpServletRequest request) {
        log.info("拉流播放代理: app:{}-stream:{}", streamPullPlay.getApp(), streamPullPlay.getStream());
        DeferredResult<R<StreamContent>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
 
        ErrorCallback<StreamInfo> callback = (code, msg, streamInfo) -> {
            if (code == InviteErrorCode.SUCCESS.getCode()) {
                R<StreamContent> r = R.ok();
                if (streamInfo != null) {
                    if (userSetting.getUseSourceIpAsStreamIp()) {
                        streamInfo = streamInfo.clone();//深拷贝
                        String host;
                        try {
                            URL url = new URL(request.getRequestURL().toString());
                            host = url.getHost();
                        } catch (MalformedURLException e) {
                            host = request.getLocalAddr();
                        }
                        streamInfo.changeStreamIp(host);
                    }
                    if (!ObjectUtils.isEmpty(streamInfo.getMediaServer().getTranscodeSuffix()) && !"null".equalsIgnoreCase(streamInfo.getMediaServer().getTranscodeSuffix())) {
                        streamInfo.setStream(streamInfo.getStream() + "_" + streamInfo.getMediaServer().getTranscodeSuffix());
                    }
                    r.setData(new StreamContent(streamInfo));
                } else {
                    r.setCode(code);
                    r.setMsg(msg);
                }
 
                result.setResult(r);
            } else {
                result.setResult(R.fail(code, msg));
            }
        };
 
        mediaServerService.streamPullPlay(streamPullPlay, callback);
        return result;
    }
 
    /**
     * 停止拉流播放
     *
     * @param streamPullPlay 拉流播放请求参数
     * @return
     */
    @Operation(summary = "停止拉流播放")
    @PostMapping("/stopStreamPullPlay")
    public AjaxResult stopStreamPullPlay(@RequestBody StreamPullPlay streamPullPlay) {
        mediaServerService.stopStreamPullPlay(streamPullPlay);
        return AjaxResult.success();
    }
 
    /**
     * 获取截图
     *
     * @param snap 截图参数
     * @return
     */
    @Operation(summary = "获取截图")
    @PostMapping("/getSnap")
    public AjaxResult getSnap(@RequestBody Snap snap) {
        ZlmMediaServer mediaServer = mediaServerService.getMediaServerForMinimumLoad(null);
        if (mediaServer == null) {
            throw new RuntimeException("无可用的流媒体服务器");
        }
        String filePath = mediaServerService.getSnap(mediaServer, snap);
        return AjaxResult.success(filePath);
    }
 
    /**
     * rtp播放
     *
     * @param rtpServerParam 创建rtp端口请求参数
     * @param request        HttpServletRequest
     * @return
     */
    @Operation(summary = "rtp播放")
    @PostMapping("/rtpPlay")
    public DeferredResult<R<StreamContent>> rtpPlay(@RequestBody RTPServerParam rtpServerParam, HttpServletRequest request) {
        log.info("rtp播放: app:{}-stream:{}", rtpServerParam.getApp(), rtpServerParam.getStreamId());
 
        if (!(LiveStreamType.HIK_SDK.getCode().equals(rtpServerParam.getType())
                || LiveStreamType.HIK_ISUP.getCode().equals(rtpServerParam.getType())
                || LiveStreamType.DAHUA_SDK.getCode().equals(rtpServerParam.getType())
        )) {
            log.error("不支持的播放类型:{}", rtpServerParam.getType());
            throw new RuntimeException("不支持的播放类型");
        }
 
        DeferredResult<R<StreamContent>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
 
        result.onTimeout(() -> {
            log.info("[rtp播放等待超时] app:{}, stream:{}", rtpServerParam.getApp(), rtpServerParam.getStreamId());
            R<StreamContent> wvpResult = R.fail();
            wvpResult.setMsg("rtp播放超时");
            result.setResult(wvpResult);
 
            inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, rtpServerParam.getId());
            mediaServerService.stopRtpPlay(rtpServerParam);
        });
 
        ErrorCallback<StreamInfo> callback = (code, msg, streamInfo) -> {
            if (code == InviteErrorCode.SUCCESS.getCode()) {
                R<StreamContent> r = R.ok();
                if (streamInfo != null) {
                    if (userSetting.getUseSourceIpAsStreamIp()) {
                        streamInfo = streamInfo.clone();//深拷贝
                        String host;
                        try {
                            URL url = new URL(request.getRequestURL().toString());
                            host = url.getHost();
                        } catch (MalformedURLException e) {
                            host = request.getLocalAddr();
                        }
                        streamInfo.changeStreamIp(host);
                    }
                    if (!ObjectUtils.isEmpty(streamInfo.getMediaServer().getTranscodeSuffix()) && !"null".equalsIgnoreCase(streamInfo.getMediaServer().getTranscodeSuffix())) {
                        streamInfo.setStream(streamInfo.getStream() + "_" + streamInfo.getMediaServer().getTranscodeSuffix());
                    }
                    r.setData(new StreamContent(streamInfo));
                } else {
                    r.setCode(code);
                    r.setMsg(msg);
                }
 
                result.setResult(r);
            } else {
                result.setResult(R.fail(code, msg));
            }
        };
 
        mediaServerService.rtpPlay(rtpServerParam, callback);
        return result;
    }
 
    /**
     * 停止rtp播放
     *
     * @param rtpServerParam 创建rtp端口请求参数
     * @return
     */
    @Operation(summary = "停止rtp播放")
    @PostMapping("/stopRtpPlay")
    public AjaxResult stopRtpPlay(@RequestBody RTPServerParam rtpServerParam) {
        log.info("停止rtp播放: id:{}", rtpServerParam.getId());
        if (!(LiveStreamType.HIK_SDK.getCode().equals(rtpServerParam.getType())
                || LiveStreamType.HIK_ISUP.getCode().equals(rtpServerParam.getType())
                || LiveStreamType.DAHUA_SDK.getCode().equals(rtpServerParam.getType())
        )) {
            log.error("不支持的播放类型:{}", rtpServerParam.getType());
            throw new RuntimeException("不支持的播放类型");
        }
        mediaServerService.stopRtpPlay(rtpServerParam);
        return AjaxResult.success();
    }
 
    /**
     * 加载文件形成播放地址
     *
     * @param id 设备id
     * @return
     */
    @GetMapping("/loadRecord/{id}")
    public DeferredResult<R<StreamContent>> loadRecord(@PathVariable Long id, HttpServletRequest request) {
        DeferredResult<R<StreamContent>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
 
        result.onTimeout(() -> {
            log.info("[加载录像文件超时] id={}", id);
            R<StreamContent> wvpResult = R.fail();
            wvpResult.setMsg("加载录像文件超时");
            result.setResult(wvpResult);
        });
 
        ErrorCallback<StreamInfo> callback = (code, msg, streamInfo) -> {
            if (code == InviteErrorCode.SUCCESS.getCode()) {
                R<StreamContent> r = R.ok();
                if (streamInfo != null) {
                    if (userSetting.getUseSourceIpAsStreamIp()) {
                        streamInfo = streamInfo.clone();//深拷贝
                        String host;
                        try {
                            URL url = new URL(request.getRequestURL().toString());
                            host = url.getHost();
                        } catch (MalformedURLException e) {
                            host = request.getLocalAddr();
                        }
                        streamInfo.changeStreamIp(host);
                    }
                    if (!ObjectUtils.isEmpty(streamInfo.getMediaServer().getTranscodeSuffix()) && !"null".equalsIgnoreCase(streamInfo.getMediaServer().getTranscodeSuffix())) {
                        streamInfo.setStream(streamInfo.getStream() + "_" + streamInfo.getMediaServer().getTranscodeSuffix());
                    }
                    r.setData(new StreamContent(streamInfo));
                } else {
                    r.setCode(code);
                    r.setMsg(msg);
                }
                result.setResult(r);
            } else {
                result.setResult(R.fail(code, msg));
            }
        };
 
        mediaServerService.loadRecord(id, callback);
        return result;
    }
 
    /**
     * 关闭流文件形成播放地址
     *
     * @param id 加载文件参数
     * @return
     */
    @GetMapping("/closeStreams/{id}")
    public AjaxResult closeStreams(@PathVariable Long id) {
        mediaServerService.closeStreams(id);
        return AjaxResult.success();
    }
 
    /**
     * 获取流媒体服务器列表
     *
     * @return
     */
    @Operation(summary = "获取流媒体服务器列表")
    @GetMapping(value = "/list")
    public AjaxResult getMediaServerList() {
        List<ZlmMediaServer> list = mediaServerService.getAll();
        return AjaxResult.success(list);
    }
 
    /**
     * 移除流媒体服务
     *
     * @param id 流媒体ID
     */
    @Operation(summary = "移除流媒体服务")
    @DeleteMapping(value = "/delete/{id}")
    public AjaxResult deleteMediaServer(@PathVariable("id") String id) {
        ZlmMediaServer mediaServer = mediaServerService.getOne(id);
        if (mediaServer == null) {
            throw new RuntimeException("流媒体不存在");
        }
        mediaServerService.delete(mediaServer);
        return AjaxResult.success();
    }
 
    /**
     * 保存流媒体服务
     *
     * @param mediaServer 流媒体信息
     */
    @Operation(summary = "保存流媒体服务")
    @PostMapping(value = "/save")
    public AjaxResult saveMediaServer(@RequestBody ZlmMediaServer mediaServer) {
        ZlmMediaServer mediaServerItemInDatabase = mediaServerService.getOneFromDatabase(mediaServer.getId());
 
        if (mediaServerItemInDatabase != null) {
            mediaServerService.update(mediaServer);
        } else {
            mediaServerService.add(mediaServer);
            // 发送事件
            MediaServerChangeEvent event = new MediaServerChangeEvent(this);
            event.setMediaServerItemList(mediaServer);
            applicationEventPublisher.publishEvent(event);
        }
 
        return AjaxResult.success();
    }
 
    /**
     * 测试流媒体服务
     *
     * @param ip     流媒体服务IP
     * @param port   流媒体服务HTT端口
     * @param secret 流媒体服务secret
     * @param type   流媒体服务类型
     * @return
     */
    @Operation(summary = "测试流媒体服务")
    @GetMapping(value = "/check")
    public AjaxResult checkMediaServer(@RequestParam String ip, @RequestParam int port, @RequestParam String secret, @RequestParam String type) {
        ZlmMediaServer mediaServer = mediaServerService.checkMediaServer(ip, port, secret, type);
        return AjaxResult.success(mediaServer);
    }
 
    /**
     * 获取流媒体服务
     *
     * @param id 流媒体服务ID
     * @return
     */
    @Operation(summary = "获取流媒体服务")
    @GetMapping(value = "/one/{id}")
    public AjaxResult getMediaServer(@PathVariable String id) {
        ZlmMediaServer mediaServer = mediaServerService.getOne(id);
        return AjaxResult.success(mediaServer);
    }
 
    /**
     * 获取流信息
     *
     * @param app           应用名
     * @param stream        流ID
     * @param mediaServerId 流媒体ID
     * @return
     */
    @Operation(summary = "获取流信息")
    @GetMapping(value = "/media_info")
    public AjaxResult getMediaInfo(@RequestParam String app, @RequestParam String stream, @RequestParam String mediaServerId) {
        Assert.hasText(app, "app参数不能为空");
        Assert.hasText(stream, "stream参数不能为空");
        Assert.hasText(mediaServerId, "mediaServerId参数不能为空");
        ZlmMediaServer mediaServer = mediaServerService.getOne(mediaServerId);
        if (mediaServer == null) {
            throw new RuntimeException("流媒体不存在");
        }
        return AjaxResult.success(mediaServerService.getMediaInfo(mediaServer, app, stream));
    }
 
    /**
     * 重启流媒体
     *
     * @param mediaServerId 流媒体ID
     * @return
     */
    @Operation(summary = "重启流媒体")
    @GetMapping(value = "/restartServer/{mediaServerId}")
    public AjaxResult restartServer(@PathVariable String mediaServerId) {
        ZlmMediaServer mediaServer = mediaServerService.getOne(mediaServerId);
        if (mediaServer == null) {
            throw new RuntimeException("流媒体不存在");
        }
        mediaServerService.restartServer(mediaServer);
        return AjaxResult.success();
    }
 
    /**
     * 获取所有在线媒体服务器
     *
     * @return
     */
    @Operation(summary = "获取所有在线媒体服务器")
    @GetMapping(value = "/getAllOnlineMediaServe")
    public AjaxResult getAllOnlineMediaServe() {
        return AjaxResult.success(mediaServerService.getAllOnlineMediaServe());
    }
 
    /**
     * 生成推流地址
     *
     * @return
     */
    @Operation(summary = "生成推流地址")
    @GetMapping(value = "/getStreamPushAddress/{id}")
    public AjaxResult getStreamPushAddress(@PathVariable Long id, String callId) {
        if (StringUtils.isEmpty(callId)) {
            return AjaxResult.error("callId不能是空");
        }
        return AjaxResult.success(mediaServerService.getStreamPushAddress(id, callId));
    }
 
    /**
     * 推流播放
     *
     * @param request
     * @param id
     * @return
     */
    @Operation(summary = "推流播放")
    @GetMapping(value = "/streamPullPush")
    public DeferredResult<R<StreamContent>> streamPullPush(HttpServletRequest request, @RequestParam Long id) {
        Assert.notNull(id, "设备ID不可为NULL");
        DeferredResult<R<StreamContent>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
        result.onTimeout(() -> {
            log.info("[等待推流超时] id={}", id);
            R<StreamContent> fail = R.fail("等待推流超时");
            result.setResult(fail);
        });
 
        mediaServerService.streamPullPush(id, (code, msg, streamInfo) -> {
            if (code == 0 && streamInfo != null) {
                if (userSetting.getUseSourceIpAsStreamIp()) {
                    streamInfo = streamInfo.clone();//深拷贝
                    String host;
                    try {
                        URL url = new URL(request.getRequestURL().toString());
                        host = url.getHost();
                    } catch (MalformedURLException e) {
                        host = request.getLocalAddr();
                    }
                    streamInfo.changeStreamIp(host);
                }
                R<StreamContent> success = R.ok(new StreamContent(streamInfo));
                result.setResult(success);
            } else {
                // 处理失败情况
                log.info("[等待推流失败] id={}, code={}, msg={}", id, code, msg);
                R<StreamContent> fail = R.fail(code, msg);
                result.setResult(fail);
            }
        });
        return result;
    }
 
    /**
     * gb28181 播放
     *
     * @param request
     * @param id      设备id
     * @return
     */
    @Operation(summary = "gb28181播放")
    @GetMapping("/startGb28181Play/{id}")
    public DeferredResult<R<StreamContent>> startGb28181Play(
            HttpServletRequest request,
            @PathVariable Long id
    ) {
        log.info("[gb28181 开始点播] id:{} ", id);
        Assert.notNull(id, "设备id");
 
        R<StreamChannel> qsDevicer = zlmStreamService.getQsDeviceInfo(id, SecurityConstants.INNER);
        if (qsDevicer.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("获取设备信息失败 id:" + id);
        }
        Assert.notNull(qsDevicer.getData(), "设备不存在 id:" + id);
 
        StreamChannel streamChannel = qsDevicer.getData();
 
        if (!Boolean.TRUE.equals(streamChannel.getDeviceOnLine())) {
            throw new RuntimeException("设备不在线 id:" + id);
        }
 
        R<Device> deviceR = remoteGb28181Service.getDeviceByDeviceId(streamChannel.getGbDeviceId(), SecurityConstants.INNER);
        if (deviceR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("gb28181 获取设备信息失败 id:" + streamChannel.getGbDeviceId());
        }
        Assert.notNull(deviceR.getData(), "gb28181 国标设备不存在 id:" + streamChannel.getGbDeviceId());
 
        if (!deviceR.getData().isOnLine()) {
            throw new RuntimeException("gb28181 国标设备不在线失败 id:" + streamChannel.getGbDeviceId());
        }
 
        R<DeviceChannel> deviceChannelR = remoteGb28181Service.getDeviceChannelByChannelId(streamChannel.getGbDeviceId(), streamChannel.getGbChannelId(), SecurityConstants.INNER);
        if (deviceChannelR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("gb28181 获取设备通道失败 gbDeviceId:" + streamChannel.getGbDeviceId() + ",gbChannelId:" + streamChannel.getGbChannelId());
        }
 
        Assert.notNull(deviceChannelR.getData(), "gb28181 获取设备通道失败不存在 gbDeviceId:" + streamChannel.getGbDeviceId() + ",gbChannelId:" + streamChannel.getGbChannelId());
 
        if (!"ON".equals(deviceChannelR.getData().getStatus())) {
            throw new RuntimeException("gb28181 国标设备通道不在线失败 gbDeviceId:" + streamChannel.getGbDeviceId() + ",gbChannelId:" + streamChannel.getGbChannelId());
        }
 
        DeferredResult<R<StreamContent>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
 
        result.onTimeout(() -> {
            log.info("[点播等待超时] gbDeviceId:{}, gbChannelId:{}, ", streamChannel.getGbDeviceId(), streamChannel.getGbChannelId());
            // 释放rtpserver
            R<StreamContent> wvpResult = R.fail();
            wvpResult.setMsg("点播超时");
            result.setResult(wvpResult);
 
            inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, streamChannel.getId());
            mediaServerService.stopGb28181Play(InviteSessionType.PLAY, streamChannel, deviceR.getData(), streamChannel.getDeviceCode());
        });
 
        ErrorCallback<StreamInfo> callback = (code, msg, streamInfo) -> {
            if (code == InviteErrorCode.SUCCESS.getCode()) {
                R<StreamContent> r = R.ok();
                if (streamInfo != null) {
                    if (userSetting.getUseSourceIpAsStreamIp()) {
                        streamInfo = streamInfo.clone();//深拷贝
                        String host;
                        try {
                            URL url = new URL(request.getRequestURL().toString());
                            host = url.getHost();
                        } catch (MalformedURLException e) {
                            host = request.getLocalAddr();
                        }
                        streamInfo.changeStreamIp(host);
                    }
                    if (!ObjectUtils.isEmpty(streamInfo.getMediaServer().getTranscodeSuffix()) && !"null".equalsIgnoreCase(streamInfo.getMediaServer().getTranscodeSuffix())) {
                        streamInfo.setStream(streamInfo.getStream() + "_" + streamInfo.getMediaServer().getTranscodeSuffix());
                    }
                    r.setData(new StreamContent(streamInfo));
                } else {
                    r.setCode(code);
                    r.setMsg(msg);
                }
 
                result.setResult(r);
            } else {
                result.setResult(R.fail(code, msg));
            }
        };
 
        streamChannel.setStreamMode(deviceR.getData().getStreamMode());
        mediaServerService.startGb28181Play(streamChannel, deviceR.getData(), callback);
        return result;
    }
 
    /**
     * gb28181 停止点播
     *
     * @param id 设备id
     * @return
     */
    @GetMapping("/stopGb28181Play/{id}")
    public AjaxResult stopGb28181Play(@PathVariable Long id) {
 
        log.info("[gb28181 停止点播] id:{} ", id);
        Assert.notNull(id, "设备id");
 
        R<StreamChannel> qsDevicer = zlmStreamService.getQsDeviceInfo(id, SecurityConstants.INNER);
        if (qsDevicer.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("获取设备信息失败 id:" + id);
        }
        Assert.notNull(qsDevicer.getData(), "设备不存在 id:" + id);
 
        StreamChannel streamChannel = qsDevicer.getData();
 
        if (!Boolean.TRUE.equals(streamChannel.getDeviceOnLine())) {
            throw new RuntimeException("设备不在线 id:" + id);
        }
 
        R<Device> deviceR = remoteGb28181Service.getDeviceByDeviceId(streamChannel.getGbDeviceId(), SecurityConstants.INNER);
        if (deviceR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("gb28181 获取设备信息失败 id:" + streamChannel.getGbDeviceId());
        }
        Assert.notNull(deviceR.getData(), "gb28181 国标设备不存在 id:" + streamChannel.getGbDeviceId());
 
        if (!deviceR.getData().isOnLine()) {
            throw new RuntimeException("gb28181 国标设备不在线失败 id:" + streamChannel.getGbDeviceId());
        }
 
        R<DeviceChannel> deviceChannelR = remoteGb28181Service.getDeviceChannelByChannelId(streamChannel.getGbDeviceId(), streamChannel.getGbChannelId(), SecurityConstants.INNER);
        if (deviceChannelR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("gb28181 获取设备通道失败 gbDeviceId:" + streamChannel.getGbDeviceId() + ",gbChannelId:" + streamChannel.getGbChannelId());
        }
 
        Assert.notNull(deviceChannelR.getData(), "gb28181 获取设备通道失败不存在 gbDeviceId:" + streamChannel.getGbDeviceId() + ",gbChannelId:" + streamChannel.getGbChannelId());
 
        if (!"ON".equals(deviceChannelR.getData().getStatus())) {
            throw new RuntimeException("gb28181 国标设备通道不在线失败 gbDeviceId:" + streamChannel.getGbDeviceId() + ",gbChannelId:" + streamChannel.getGbChannelId());
        }
 
        mediaServerService.stopGb28181Play(InviteSessionType.PLAY, streamChannel, deviceR.getData(), streamChannel.getDeviceCode());
        JSONObject json = new JSONObject();
        json.put("deviceId", streamChannel.getGbDeviceId());
        json.put("channelId", streamChannel.getGbChannelId());
        return AjaxResult.success(json);
    }
 
    /**
     * gb28181 播放(基于GbDevice,不依赖QS,按国标编码播放)
     *
     * @param request
     * @param gbDeviceId  国标设备编码
     * @param gbChannelId 国标通道编码
     * @return
     */
    @Operation(summary = "gb28181播放(按国标编码)")
    @GetMapping("/startGb28181PlayByGbDeviceId/{gbDeviceId}/{gbChannelId}")
    public DeferredResult<R<StreamContent>> startGb28181PlayByGbDeviceId(
            HttpServletRequest request,
            @PathVariable String gbDeviceId,
            @PathVariable String gbChannelId
    ) {
        log.info("[gb28181 开始点播] gbDeviceId:{}, gbChannelId:{}", gbDeviceId, gbChannelId);
        Assert.hasText(gbDeviceId, "国标设备编码不可为空");
        Assert.hasText(gbChannelId, "国标通道编码不可为空");
 
        // 1. 查询 GbChannel 配置
        R<GbChannelDTO> channelR = remoteGb28181Service.getGbChannel(gbDeviceId, gbChannelId, SecurityConstants.INNER);
        if (channelR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("获取GbChannel配置失败 gbDeviceId:" + gbDeviceId + " gbChannelId:" + gbChannelId
                    + "。设备注册后会自动创建,请确认设备已上线并完成目录同步。");
        }
        Assert.notNull(channelR.getData(), "GbChannel不存在 gbDeviceId:" + gbDeviceId + " gbChannelId:" + gbChannelId);
 
        StreamChannel streamChannel = ZlmStreamService.toStreamChannel(channelR.getData());
 
        // 2. 查询国标设备
        R<Device> deviceR = remoteGb28181Service.getDeviceByDeviceId(gbDeviceId, SecurityConstants.INNER);
        if (deviceR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("gb28181 获取设备信息失败 deviceId:" + gbDeviceId);
        }
        Assert.notNull(deviceR.getData(), "gb28181 国标设备不存在 deviceId:" + gbDeviceId);
 
        if (!deviceR.getData().isOnLine()) {
            throw new RuntimeException("gb28181 国标设备不在线 deviceId:" + gbDeviceId);
        }
 
        // 3. 查询国标通道
        R<DeviceChannel> deviceChannelR = remoteGb28181Service.getDeviceChannelByChannelId(gbDeviceId, gbChannelId, SecurityConstants.INNER);
        if (deviceChannelR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("gb28181 获取设备通道失败 gbDeviceId:" + gbDeviceId + " gbChannelId:" + gbChannelId);
        }
        Assert.notNull(deviceChannelR.getData(), "gb28181 国标设备通道不存在 gbDeviceId:" + gbDeviceId + " gbChannelId:" + gbChannelId);
 
        if (!"ON".equals(deviceChannelR.getData().getStatus())) {
            throw new RuntimeException("gb28181 国标设备通道不在线 gbDeviceId:" + gbDeviceId + " gbChannelId:" + gbChannelId);
        }
 
        DeferredResult<R<StreamContent>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
 
        result.onTimeout(() -> {
            log.info("[点播等待超时] gbDeviceId:{}, gbChannelId:{}", gbDeviceId, gbChannelId);
            R<StreamContent> fail = R.fail();
            fail.setMsg("点播超时");
            result.setResult(fail);
 
            inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, streamChannel.getId());
            mediaServerService.stopGb28181PlayByGbChannel(InviteSessionType.PLAY, streamChannel, deviceR.getData(), streamChannel.getDeviceCode());
        });
 
        ErrorCallback<StreamInfo> callback = (code, msg, streamInfo) -> {
            if (code == InviteErrorCode.SUCCESS.getCode()) {
                R<StreamContent> r = R.ok();
                if (streamInfo != null) {
                    if (userSetting.getUseSourceIpAsStreamIp()) {
                        streamInfo = streamInfo.clone();
                        String host;
                        try {
                            URL url = new URL(request.getRequestURL().toString());
                            host = url.getHost();
                        } catch (MalformedURLException e) {
                            host = request.getLocalAddr();
                        }
                        streamInfo.changeStreamIp(host);
                    }
                    if (!ObjectUtils.isEmpty(streamInfo.getMediaServer().getTranscodeSuffix())
                            && !"null".equalsIgnoreCase(streamInfo.getMediaServer().getTranscodeSuffix())) {
                        streamInfo.setStream(streamInfo.getStream() + "_" + streamInfo.getMediaServer().getTranscodeSuffix());
                    }
                    r.setData(new StreamContent(streamInfo));
                } else {
                    r.setCode(code);
                    r.setMsg(msg);
                }
                result.setResult(r);
            } else {
                result.setResult(R.fail(code, msg));
            }
        };
 
        mediaServerService.startGb28181PlayByGbChannel(streamChannel, deviceR.getData(), callback);
        return result;
    }
 
    /**
     * gb28181 停止点播(基于GbDevice,不依赖QS,按国标编码停止)
     *
     * @param gbDeviceId  国标设备编码
     * @param gbChannelId 国标通道编码
     * @return
     */
    @Operation(summary = "gb28181停止点播(按国标编码)")
    @GetMapping("/stopGb28181PlayByGbDeviceId/{gbDeviceId}/{gbChannelId}")
    public AjaxResult stopGb28181PlayByGbDeviceId(
            @PathVariable String gbDeviceId,
            @PathVariable String gbChannelId
    ) {
        log.info("[gb28181 停止点播] gbDeviceId:{}, gbChannelId:{}", gbDeviceId, gbChannelId);
        Assert.hasText(gbDeviceId, "国标设备编码不可为空");
        Assert.hasText(gbChannelId, "国标通道编码不可为空");
 
        // 1. 查询 GbChannel 配置
        R<GbChannelDTO> channelR = remoteGb28181Service.getGbChannel(gbDeviceId, gbChannelId, SecurityConstants.INNER);
        if (channelR.getCode() != Constants.SUCCESS || channelR.getData() == null) {
            throw new RuntimeException("GbChannel不存在 gbDeviceId:" + gbDeviceId + " gbChannelId:" + gbChannelId);
        }
 
        StreamChannel streamChannel = ZlmStreamService.toStreamChannel(channelR.getData());
 
        // 2. 查询国标设备
        R<Device> deviceR = remoteGb28181Service.getDeviceByDeviceId(gbDeviceId, SecurityConstants.INNER);
        if (deviceR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("gb28181 获取设备信息失败 deviceId:" + gbDeviceId);
        }
        Assert.notNull(deviceR.getData(), "gb28181 国标设备不存在 deviceId:" + gbDeviceId);
 
        // 3. 查询国标通道
        R<DeviceChannel> deviceChannelR = remoteGb28181Service.getDeviceChannelByChannelId(gbDeviceId, gbChannelId, SecurityConstants.INNER);
        if (deviceChannelR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("gb28181 获取设备通道失败 gbDeviceId:" + gbDeviceId + " gbChannelId:" + gbChannelId);
        }
        Assert.notNull(deviceChannelR.getData(), "gb28181 国标设备通道不存在 gbDeviceId:" + gbDeviceId + " gbChannelId:" + gbChannelId);
 
        mediaServerService.stopGb28181PlayByGbChannel(InviteSessionType.PLAY, streamChannel,
                deviceR.getData(), streamChannel.getDeviceCode());
 
        JSONObject json = new JSONObject();
        json.put("gbDeviceId", gbDeviceId);
        json.put("gbChannelId", gbChannelId);
        return AjaxResult.success(json);
    }
 
    /**
     * gb28181 播放(基于GbChannel主键ID)
     *
     * @param request
     * @param channelId GbChannel主键ID
     * @return
     */
    @Operation(summary = "gb28181播放(按通道主键ID)")
    @GetMapping("/startGb28181PlayByChannelId/{channelId}")
    public DeferredResult<R<StreamContent>> startGb28181PlayByChannelId(
            HttpServletRequest request,
            @PathVariable Long channelId
    ) {
        log.info("[gb28181 开始点播] channelId:{}", channelId);
        Assert.notNull(channelId, "通道ID不可为空");
 
        // 1. 根据主键ID查询 GbChannel
        R<GbChannelDTO> channelR = remoteGb28181Service.getGbChannelById(channelId, SecurityConstants.INNER);
        if (channelR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("获取GbChannel失败 channelId:" + channelId);
        }
        Assert.notNull(channelR.getData(), "GbChannel不存在 channelId:" + channelId);
 
        StreamChannel streamChannel = ZlmStreamService.toStreamChannel(channelR.getData());
        String gbDeviceId = streamChannel.getGbDeviceId();
        String gbChannelId = streamChannel.getGbChannelId();
 
        // 2. 查询国标设备
        R<Device> deviceR = remoteGb28181Service.getDeviceByDeviceId(gbDeviceId, SecurityConstants.INNER);
        if (deviceR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("gb28181 获取设备信息失败 deviceId:" + gbDeviceId);
        }
        Assert.notNull(deviceR.getData(), "gb28181 国标设备不存在 deviceId:" + gbDeviceId);
 
        if (!deviceR.getData().isOnLine()) {
            throw new RuntimeException("gb28181 国标设备不在线 deviceId:" + gbDeviceId);
        }
 
        // 3. 查询国标通道
        R<DeviceChannel> deviceChannelR = remoteGb28181Service.getDeviceChannelByChannelId(gbDeviceId, gbChannelId, SecurityConstants.INNER);
        if (deviceChannelR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("gb28181 获取设备通道失败 gbDeviceId:" + gbDeviceId + " gbChannelId:" + gbChannelId);
        }
        Assert.notNull(deviceChannelR.getData(), "gb28181 国标设备通道不存在 gbDeviceId:" + gbDeviceId + " gbChannelId:" + gbChannelId);
 
        if (!"ON".equals(deviceChannelR.getData().getStatus())) {
            throw new RuntimeException("gb28181 国标设备通道不在线 gbDeviceId:" + gbDeviceId + " gbChannelId:" + gbChannelId);
        }
 
        DeferredResult<R<StreamContent>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
 
        result.onTimeout(() -> {
            log.info("[点播等待超时] channelId:{}, gbDeviceId:{}, gbChannelId:{}", channelId, gbDeviceId, gbChannelId);
            R<StreamContent> fail = R.fail();
            fail.setMsg("点播超时");
            result.setResult(fail);
 
            inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, streamChannel.getId());
            mediaServerService.stopGb28181PlayByGbChannel(InviteSessionType.PLAY, streamChannel, deviceR.getData(), streamChannel.getDeviceCode());
        });
 
        ErrorCallback<StreamInfo> callback = (code, msg, streamInfo) -> {
            if (code == InviteErrorCode.SUCCESS.getCode()) {
                R<StreamContent> r = R.ok();
                if (streamInfo != null) {
                    if (userSetting.getUseSourceIpAsStreamIp()) {
                        streamInfo = streamInfo.clone();
                        String host;
                        try {
                            URL url = new URL(request.getRequestURL().toString());
                            host = url.getHost();
                        } catch (MalformedURLException e) {
                            host = request.getLocalAddr();
                        }
                        streamInfo.changeStreamIp(host);
                    }
                    if (!ObjectUtils.isEmpty(streamInfo.getMediaServer().getTranscodeSuffix())
                            && !"null".equalsIgnoreCase(streamInfo.getMediaServer().getTranscodeSuffix())) {
                        streamInfo.setStream(streamInfo.getStream() + "_" + streamInfo.getMediaServer().getTranscodeSuffix());
                    }
                    r.setData(new StreamContent(streamInfo));
                } else {
                    r.setCode(code);
                    r.setMsg(msg);
                }
                result.setResult(r);
            } else {
                result.setResult(R.fail(code, msg));
            }
        };
 
        mediaServerService.startGb28181PlayByGbChannel(streamChannel, deviceR.getData(), callback);
        return result;
    }
 
    /**
     * gb28181 停止点播(基于GbChannel主键ID)
     *
     * @param channelId GbChannel主键ID
     * @return
     */
    @Operation(summary = "gb28181停止点播(按通道主键ID)")
    @GetMapping("/stopGb28181PlayByChannelId/{channelId}")
    public AjaxResult stopGb28181PlayByChannelId(@PathVariable Long channelId) {
        log.info("[gb28181 停止点播] channelId:{}", channelId);
        Assert.notNull(channelId, "通道ID不可为空");
 
        // 1. 根据主键ID查询 GbChannel
        R<GbChannelDTO> channelR = remoteGb28181Service.getGbChannelById(channelId, SecurityConstants.INNER);
        if (channelR.getCode() != Constants.SUCCESS || channelR.getData() == null) {
            throw new RuntimeException("GbChannel不存在 channelId:" + channelId);
        }
 
        StreamChannel streamChannel = ZlmStreamService.toStreamChannel(channelR.getData());
        String gbDeviceId = streamChannel.getGbDeviceId();
        String gbChannelId = streamChannel.getGbChannelId();
 
        // 2. 查询国标设备
        R<Device> deviceR = remoteGb28181Service.getDeviceByDeviceId(gbDeviceId, SecurityConstants.INNER);
        if (deviceR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("gb28181 获取设备信息失败 deviceId:" + gbDeviceId);
        }
        Assert.notNull(deviceR.getData(), "gb28181 国标设备不存在 deviceId:" + gbDeviceId);
 
        // 3. 查询国标通道
        R<DeviceChannel> deviceChannelR = remoteGb28181Service.getDeviceChannelByChannelId(gbDeviceId, gbChannelId, SecurityConstants.INNER);
        if (deviceChannelR.getCode() != Constants.SUCCESS) {
            throw new RuntimeException("gb28181 获取设备通道失败 gbDeviceId:" + gbDeviceId + " gbChannelId:" + gbChannelId);
        }
        Assert.notNull(deviceChannelR.getData(), "gb28181 国标设备通道不存在 gbDeviceId:" + gbDeviceId + " gbChannelId:" + gbChannelId);
 
        mediaServerService.stopGb28181PlayByGbChannel(InviteSessionType.PLAY, streamChannel,
                deviceR.getData(), streamChannel.getDeviceCode());
 
        JSONObject json = new JSONObject();
        json.put("channelId", channelId);
        json.put("gbDeviceId", gbDeviceId);
        json.put("gbChannelId", gbChannelId);
        return AjaxResult.success(json);
    }
 
    /**
     * 拉流代理(通过通道ID,简化传参)
     *
     * @param request   HttpServletRequest
     * @param channelId 通道ID
     * @return
     */
    @Operation(summary = "拉流代理(通过通道ID,简化传参)")
    @PostMapping("/streamPullPlayByChannelId/{channelId}")
    public DeferredResult<R<StreamContent>> streamPullPlayByChannelId(
            HttpServletRequest request,
            @PathVariable String channelId
    ) {
        log.info("[拉流代理-通道ID] channelId:{}", channelId);
        Assert.hasText(channelId, "通道ID不可为空");
 
        DeferredResult<R<StreamContent>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
 
        ErrorCallback<StreamInfo> callback = (code, msg, streamInfo) -> {
            if (code == InviteErrorCode.SUCCESS.getCode()) {
                R<StreamContent> r = R.ok();
                if (streamInfo != null) {
                    if (userSetting.getUseSourceIpAsStreamIp()) {
                        streamInfo = streamInfo.clone();
                        String host;
                        try {
                            URL url = new URL(request.getRequestURL().toString());
                            host = url.getHost();
                        } catch (MalformedURLException e) {
                            host = request.getLocalAddr();
                        }
                        streamInfo.changeStreamIp(host);
                    }
                    if (!ObjectUtils.isEmpty(streamInfo.getMediaServer().getTranscodeSuffix())
                            && !"null".equalsIgnoreCase(streamInfo.getMediaServer().getTranscodeSuffix())) {
                        streamInfo.setStream(streamInfo.getStream() + "_" + streamInfo.getMediaServer().getTranscodeSuffix());
                    }
                    r.setData(new StreamContent(streamInfo));
                } else {
                    r.setCode(code);
                    r.setMsg(msg);
                }
                result.setResult(r);
            } else {
                result.setResult(R.fail(code, msg));
            }
        };
 
        mediaServerService.streamPullPlayByChannelId(channelId, callback);
        return result;
    }
 
    /**
     * 停止拉流代理(通过通道ID)
     *
     * @param channelId 通道ID
     * @return
     */
    @Operation(summary = "停止拉流代理(通过通道ID)")
    @PostMapping("/stopStreamPullPlayByChannelId/{channelId}")
    public AjaxResult stopStreamPullPlayByChannelId(@PathVariable String channelId) {
        log.info("[停止拉流代理-通道ID] channelId:{}", channelId);
        Assert.hasText(channelId, "通道ID不可为空");
        mediaServerService.stopStreamPullPlayByChannelId(channelId);
        return AjaxResult.success();
    }
 
}