648540858
2022-11-21 6b03568c5dd128a3d71c02fb1a3a76a4344a4920
src/main/java/com/genersoft/iot/vmp/media/zlm/ZLMHttpHookListener.java
@@ -7,9 +7,10 @@
import com.genersoft.iot.vmp.conf.exception.SsrcTransactionNotFoundException;
import com.genersoft.iot.vmp.gb28181.bean.*;
import com.genersoft.iot.vmp.gb28181.event.EventPublisher;
import com.genersoft.iot.vmp.gb28181.session.AudioBroadcastManager;
import com.genersoft.iot.vmp.gb28181.session.VideoStreamSessionManager;
import com.genersoft.iot.vmp.gb28181.transmit.cmd.ISIPCommanderForPlatform;
import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommanderFroPlatform;
import com.genersoft.iot.vmp.media.zlm.dto.HookType;
import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem;
import com.genersoft.iot.vmp.media.zlm.dto.StreamAuthorityInfo;
@@ -49,7 +50,13 @@
   private SIPCommander cmder;
   @Autowired
   private SIPCommanderFroPlatform commanderFroPlatform;
   private ISIPCommanderForPlatform commanderFroPlatform;
   @Autowired
   private AudioBroadcastManager audioBroadcastManager;
   @Autowired
   private ZLMRTPServerFactory zlmrtpServerFactory;
   @Autowired
   private IPlayService playService;
@@ -183,7 +190,7 @@
      if (!"rtp".equals(param.getApp())) {
         if (userSetting.getPushAuthority()) {
// 推流鉴权
            // 推流鉴权
            if (param.getParams() == null) {
               logger.info("推流鉴权失败: 缺少不要参数:sign=md5(user表的pushKey)");
               ret.put("code", 401);
@@ -282,9 +289,9 @@
      JSONObject json = (JSONObject) JSON.toJSON(param);
      taskExecutor.execute(()->{
      taskExecutor.execute(()-> {
         ZlmHttpHookSubscribe.Event subscribe = this.subscribe.sendNotify(HookType.on_stream_changed, json);
         if (subscribe != null ) {
         if (subscribe != null) {
            MediaServerItem mediaInfo = mediaServerService.getOne(param.getMediaServerId());
            if (mediaInfo != null) {
               subscribe.response(mediaInfo, json);
@@ -300,43 +307,166 @@
               StreamAuthorityInfo streamAuthorityInfo = redisCatchStorage.getStreamAuthorityInfo(param.getApp(), param.getStream());
               if (streamAuthorityInfo == null) {
                  streamAuthorityInfo = StreamAuthorityInfo.getInstanceByHook(param);
               }else {
               } else {
                  streamAuthorityInfo.setOriginType(param.getOriginType());
                  streamAuthorityInfo.setOriginTypeStr(param.getOriginTypeStr());
               }
               redisCatchStorage.updateStreamAuthorityInfo(param.getApp(), param.getStream(), streamAuthorityInfo);
            }
         }else {
         } else {
            redisCatchStorage.removeStreamAuthorityInfo(param.getApp(), param.getStream());
         }
      });
         if ("rtsp".equals(param.getSchema())){
            if (param.isRegist()) {
               mediaServerService.addCount(param.getMediaServerId());
            }else {
               mediaServerService.removeCount(param.getMediaServerId());
      if ("rtsp".equals(param.getSchema())){
         logger.info("on_stream_changed:注册->{}, app->{}, stream->{}", param.isRegist(), param.getApp(), param.getStream());
         if (param.isRegist()) {
            mediaServerService.addCount(param.getMediaServerId());
         }else {
            mediaServerService.removeCount(param.getMediaServerId());
         }
         if (param.getOriginType() == OriginType.PULL.ordinal()
               || param.getOriginType() == OriginType.FFMPEG_PULL.ordinal()) {
            // 设置拉流代理上线/离线
            streamProxyService.updateStatus(param.isRegist(), param.getApp(), param.getStream());
         }
         if ("rtp".equals(param.getApp()) && !param.isRegist() ) {
            StreamInfo streamInfo = redisCatchStorage.queryPlayByStreamId(param.getStream());
            if (streamInfo!=null){
               redisCatchStorage.stopPlay(streamInfo);
               storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId());
            }else{
               streamInfo = redisCatchStorage.queryPlayback(null, null, param.getStream(), null);
               if (streamInfo != null) {
                  redisCatchStorage.stopPlayback(streamInfo.getDeviceID(), streamInfo.getChannelId(),
                        streamInfo.getStream(), null);
               }
            }
            if (param.getOriginType() == OriginType.PULL.ordinal()
                  || param.getOriginType() == OriginType.FFMPEG_PULL.ordinal()) {
               // 设置拉流代理上线/离线
               streamProxyService.updateStatus(param.isRegist(), param.getApp(), param.getStream());
            }
            if ("rtp".equals(param.getApp()) && !param.isRegist() ) {
               StreamInfo streamInfo = redisCatchStorage.queryPlayByStreamId(param.getStream());
               if (streamInfo!=null){
                  redisCatchStorage.stopPlay(streamInfo);
                  storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId());
               }else{
                  streamInfo = redisCatchStorage.queryPlayback(null, null, param.getStream(), null);
                  if (streamInfo != null) {
                     redisCatchStorage.stopPlayback(streamInfo.getDeviceID(), streamInfo.getChannelId(),
                           streamInfo.getStream(), null);
         }else if ("broadcast".equals(param.getApp())){
            // 语音对讲推流  stream需要满足格式deviceId_channelId
            if (param.isRegist() && param.getStream().indexOf("_") > 0) {
               String[] streamArray = param.getStream().split("_");
               if (streamArray.length == 2) {
                  String deviceId = streamArray[0];
                  String channelId = streamArray[1];
                  Device device = deviceService.getDevice(deviceId);
                  if (device != null) {
                     DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
                     if (deviceChannel != null) {
                        if (audioBroadcastManager.exit(deviceId, channelId)) {
                           // 直接推流
                           SendRtpItem sendRtpItem =  redisCatchStorage.querySendRTPServer(null, null, param.getStream(), null);
                           if (sendRtpItem == null) {
                              // TODO 可能数据错误,重新开启语音通道
                           }else {
                              String is_Udp = sendRtpItem.isTcp() ? "0" : "1";
                              MediaServerItem mediaInfo = mediaServerService.getOne(sendRtpItem.getMediaServerId());
                              logger.info("rtp/{}开始向上级推流, 目标={}:{},SSRC={}", sendRtpItem.getStreamId(), sendRtpItem.getIp(), sendRtpItem.getPort(), sendRtpItem.getSsrc());
                              Map<String, Object> sendParam = new HashMap<>(12);
                              sendParam.put("vhost","__defaultVhost__");
                              sendParam.put("app",sendRtpItem.getApp());
                              sendParam.put("stream",sendRtpItem.getStreamId());
                              sendParam.put("ssrc", sendRtpItem.getSsrc());
                              sendParam.put("src_port", sendRtpItem.getLocalPort());
                              sendParam.put("pt", sendRtpItem.getPt());
                              sendParam.put("use_ps", sendRtpItem.isUsePs() ? "1" : "0");
                              sendParam.put("only_audio", sendRtpItem.isOnlyAudio() ? "1" : "0");
                              JSONObject jsonObject;
                              if (sendRtpItem.isTcpActive()) {
                                 jsonObject = zlmrtpServerFactory.startSendRtpPassive(mediaInfo, sendParam);
                              } else {
                                 sendParam.put("is_udp", is_Udp);
                                 sendParam.put("dst_url", sendRtpItem.getIp());
                                 sendParam.put("dst_port", sendRtpItem.getPort());
                                 jsonObject = zlmrtpServerFactory.startSendRtpStream(mediaInfo, sendParam);
                              }
                              if (jsonObject != null && jsonObject.getInteger("code") == 0) {
                                 logger.info("[语音对讲] 自动推流成功, device: {}, channel: {}", deviceId, channelId);
                              }else {
                                 logger.info("[语音对讲] 推流失败, 结果: {}", jsonObject);
                              }
                           }
                        }else {
                           // 开启语音对讲通道
                           try {
                              playService.audioBroadcastCmd(device, channelId, 60, (msg)->{
                                 logger.info("[语音对讲] 通道建立成功, device: {}, channel: {}", deviceId, channelId);
                              });
                           } catch (InvalidArgumentException | ParseException | SipException e) {
                              logger.error("[命令发送失败] 语音对讲: {}", e.getMessage());
                           }
                        }
                     }
                  }
               }
            }else {
               if (!"rtp".equals(param.getApp())){
                  String type = OriginType.values()[param.getOriginType()].getType();
                  MediaServerItem mediaServerItem = mediaServerService.getOne(param.getMediaServerId());
            }
         }else if ("talk".equals(param.getApp())){
            // 语音对讲推流  stream需要满足格式deviceId_channelId
            if (param.isRegist() && param.getStream().indexOf("_") > 0) {
               String[] streamArray = param.getStream().split("_");
               if (streamArray.length == 2) {
                  String deviceId = streamArray[0];
                  String channelId = streamArray[1];
                  Device device = deviceService.getDevice(deviceId);
                  if (device != null) {
                     DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
                     if (deviceChannel != null) {
                        if (audioBroadcastManager.exit(deviceId, channelId)) {
                           // 直接推流
                           SendRtpItem sendRtpItem =  redisCatchStorage.querySendRTPServer(null, null, param.getStream(), null);
                           if (sendRtpItem == null) {
                              // TODO 可能数据错误,重新开启语音通道
                           }else {
                              MediaServerItem mediaInfo = mediaServerService.getOne(sendRtpItem.getMediaServerId());
                              logger.info("rtp/{}开始向上级推流, 目标={}:{},SSRC={}", sendRtpItem.getStreamId(), sendRtpItem.getIp(), sendRtpItem.getPort(), sendRtpItem.getSsrc());
                              Map<String, Object> sendParam = new HashMap<>(12);
                              sendParam.put("vhost","__defaultVhost__");
                              sendParam.put("app",sendRtpItem.getApp());
                              sendParam.put("stream",sendRtpItem.getStreamId());
                              sendParam.put("ssrc", sendRtpItem.getSsrc());
                              sendParam.put("src_port", sendRtpItem.getLocalPort());
                              sendParam.put("pt", sendRtpItem.getPt());
                              sendParam.put("use_ps", sendRtpItem.isUsePs() ? "1" : "0");
                              sendParam.put("only_audio", sendRtpItem.isOnlyAudio() ? "1" : "0");
                              JSONObject jsonObject;
                              if (sendRtpItem.isTcpActive()) {
                                 jsonObject = zlmrtpServerFactory.startSendRtpPassive(mediaInfo, sendParam);
                              } else {
                                 sendParam.put("is_udp", sendRtpItem.isTcp() ? "0" : "1");
                                 sendParam.put("dst_url", sendRtpItem.getIp());
                                 sendParam.put("dst_port", sendRtpItem.getPort());
                                 jsonObject = zlmrtpServerFactory.startSendRtpStream(mediaInfo, sendParam);
                              }
                              if (jsonObject != null && jsonObject.getInteger("code") == 0) {
                                 logger.info("[语音对讲] 自动推流成功, device: {}, channel: {}", deviceId, channelId);
                              }
                           }
                        }else {
                           // 开启语音对讲通道
                           MediaServerItem mediaServerItem = mediaServerService.getOne(param.getMediaServerId());
                           playService.talk(mediaServerItem, device, channelId, (mediaServer, jsonObject)->{
                              System.out.println("开始推流");
                           }, eventResult -> {
                              System.out.println(eventResult.msg);
                           }, ()->{
                              System.out.println("超时");
                           });
                        }
                     }
                  }
               }
            }
         }else{
            if (!"rtp".equals(param.getApp())){
               String type = OriginType.values()[param.getOriginType()].getType();
               MediaServerItem mediaServerItem = mediaServerService.getOne(param.getMediaServerId());
                  if (mediaServerItem != null){
                     if (param.isRegist()) {
@@ -346,7 +476,7 @@
                           callId = streamAuthorityInfo.getCallId();
                        }
                        StreamInfo streamInfoByAppAndStream = mediaService.getStreamInfoByAppAndStream(mediaServerItem,
                              param.getApp(), param.getStream(), tracks, callId);
                              param.getApp(), param.getStream(), param.getTracks(), callId);
                        param.setStreamInfo(streamInfoByAppAndStream);
                        redisCatchStorage.addStream(mediaServerItem, type, param.getApp(), param.getStream(), param);
                        if (param.getOriginType() == OriginType.RTSP_PUSH.ordinal()
@@ -357,7 +487,8 @@
                        }
                     }else {
                        // 兼容流注销时类型从redis记录获取
                        OnStreamChangedHookParam onStreamChangedHookParam = redisCatchStorage.getStreamInfo(param.getApp(), param.getStream(), param.getMediaServerId());
                        OnStreamChangedHookParam onStreamChangedHookParam = redisCatchStorage.getStreamInfo(
                              param.getApp(), param.getStream(), param.getMediaServerId());
                        if (onStreamChangedHookParam != null) {
                           type = OriginType.values()[onStreamChangedHookParam.getOriginType()].getType();
                           redisCatchStorage.removeStream(mediaServerItem.getId(), type, param.getApp(), param.getStream());
@@ -390,21 +521,28 @@
                        ParentPlatform platform = storager.queryParentPlatByServerGBId(platformId);
                        Device device = deviceService.getDevice(platformId);
                        try {
                           if (platform != null) {
                              commanderFroPlatform.streamByeCmd(platform, sendRtpItem);
                     try {
                        if (platform != null) {
                           commanderFroPlatform.streamByeCmd(platform, sendRtpItem);
                        }else {
                           if ("talk".equals(param.getApp()) && sendRtpItem.isOnlyAudio()) {
                              AudioBroadcastCatch audioBroadcastCatch = audioBroadcastManager.get(sendRtpItem.getDeviceId(), sendRtpItem.getChannelId());
                              if (device != null && audioBroadcastCatch != null) {
//                                 cmder.streamByeCmd(device, sendRtpItem.getChannelId(), audioBroadcastCatch.getSipTransactionInfo(), null);
                              }
                           }else {
                              cmder.streamByeCmd(device, sendRtpItem.getChannelId(), param.getStream(), sendRtpItem.getCallId());
                              cmder.streamByeCmd(device, null, null, sendRtpItem.getCallId());
                           }
                        } catch (SipException | InvalidArgumentException | ParseException | SsrcTransactionNotFoundException e) {
                           logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
                        }
                     } catch (SipException | InvalidArgumentException | ParseException | SsrcTransactionNotFoundException e) {
                        logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
                     }
                  }
               }
            }
         }
      });
      }
      JSONObject ret = new JSONObject();
      ret.put("code", 0);
@@ -436,6 +574,9 @@
               if (sendRtpItems.size() > 0) {
                  for (SendRtpItem sendRtpItem : sendRtpItems) {
                     ParentPlatform parentPlatform = storager.queryParentPlatByServerGBId(sendRtpItem.getPlatformId());
                     if (parentPlatform == null) {
                        continue;
                     }
                     try {
                        commanderFroPlatform.streamByeCmd(parentPlatform, sendRtpItem.getCallId());
                     } catch (SipException | InvalidArgumentException | ParseException e) {
@@ -568,8 +709,6 @@
   public JSONObject onServerStarted(HttpServletRequest request, @RequestBody JSONObject jsonObject){
      jsonObject.put("ip", request.getRemoteAddr());
      System.out.println(jsonObject.toJSONString()
      );
      ZLMServerConfig zlmServerConfig = JSON.to(ZLMServerConfig.class, jsonObject);
      zlmServerConfig.setIp(request.getRemoteAddr());
      logger.info("[ZLM HOOK] zlm 启动 " + zlmServerConfig.getGeneralMediaServerId());
@@ -632,8 +771,7 @@
   @ResponseBody
   @PostMapping(value = "/on_rtp_server_timeout", produces = "application/json;charset=UTF-8")
   public JSONObject onRtpServerTimeout(HttpServletRequest request, @RequestBody OnRtpServerTimeoutHookParam param){
      System.out.println(param);
      logger.info("[ZLM HOOK] rtpServer收流超时:{}->{}({})", param.getMediaServerId(), param.getStream_id(), param.getSsrc());
      logger.info("[ZLM HOOK] rtpServer rtp超时:{}->{}({})", param.getMediaServerId(), param.getStream_id(), param.getSsrc());
      JSONObject ret = new JSONObject();
      ret.put("code", 0);