From e78c402a248ff252ee93e724396c62d806087fab Mon Sep 17 00:00:00 2001 From: 648540858 <648540858@qq.com> Date: 星期日, 03 七月 2022 10:32:33 +0800 Subject: [PATCH] Merge remote-tracking branch 'origin/wvp-28181-2.0' into commercial --- src/main/java/com/genersoft/iot/vmp/service/impl/PlayServiceImpl.java | 211 ++++++++++++++++++++++++++++++++++++---------------- 1 files changed, 144 insertions(+), 67 deletions(-) diff --git a/src/main/java/com/genersoft/iot/vmp/service/impl/PlayServiceImpl.java b/src/main/java/com/genersoft/iot/vmp/service/impl/PlayServiceImpl.java index a647c84..b944375 100644 --- a/src/main/java/com/genersoft/iot/vmp/service/impl/PlayServiceImpl.java +++ b/src/main/java/com/genersoft/iot/vmp/service/impl/PlayServiceImpl.java @@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject; import com.genersoft.iot.vmp.common.StreamInfo; import com.genersoft.iot.vmp.conf.DynamicTask; +import com.genersoft.iot.vmp.conf.SipConfig; import com.genersoft.iot.vmp.conf.UserSetting; import com.genersoft.iot.vmp.gb28181.bean.*; import com.genersoft.iot.vmp.gb28181.event.SipSubscribe; @@ -14,12 +15,15 @@ import com.genersoft.iot.vmp.gb28181.transmit.callback.RequestMessage; 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.gb28181.utils.DateUtil; +import com.genersoft.iot.vmp.media.zlm.ZLMRTPServerFactory; +import com.genersoft.iot.vmp.utils.DateUtil; import com.genersoft.iot.vmp.media.zlm.AssistRESTfulUtils; import com.genersoft.iot.vmp.media.zlm.ZLMHttpHookSubscribe; import com.genersoft.iot.vmp.media.zlm.ZLMRESTfulUtils; import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem; import com.genersoft.iot.vmp.service.IMediaServerService; +import com.genersoft.iot.vmp.service.IMediaService; +import com.genersoft.iot.vmp.service.IPlayService; import com.genersoft.iot.vmp.service.bean.InviteTimeOutCallback; import com.genersoft.iot.vmp.service.bean.PlayBackCallback; import com.genersoft.iot.vmp.service.bean.PlayBackResult; @@ -31,8 +35,6 @@ import com.genersoft.iot.vmp.vmanager.bean.WVPResult; import com.genersoft.iot.vmp.vmanager.gb28181.play.bean.AudioBroadcastEvent; import com.genersoft.iot.vmp.vmanager.gb28181.play.bean.PlayResult; -import com.genersoft.iot.vmp.service.IMediaService; -import com.genersoft.iot.vmp.service.IPlayService; import gov.nist.javax.sip.stack.SIPDialog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,9 +46,14 @@ import org.springframework.web.context.request.async.DeferredResult; import javax.sip.ResponseEvent; +import javax.sip.SipException; import java.io.FileNotFoundException; import java.math.BigDecimal; +import java.text.ParseException; +import java.math.RoundingMode; import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; @SuppressWarnings(value = {"rawtypes", "unchecked"}) @Service @@ -70,7 +77,7 @@ private IRedisCatchStorage redisCatchStorage; @Autowired - private RedisUtil redis; + private ZLMRTPServerFactory zlmrtpServerFactory; @Autowired private DeferredResultHolder resultHolder; @@ -94,7 +101,13 @@ private UserSetting userSetting; @Autowired + private SipConfig sipConfig; + + @Autowired private DynamicTask dynamicTask; + + @Autowired + private ZLMHttpHookSubscribe subscribe; @@ -129,36 +142,19 @@ result.onCompletion(()->{ // 鐐规挱缁撴潫鏃惰皟鐢ㄦ埅鍥炬帴鍙� // TODO 搴旇鍦ㄤ笂娴佹椂璋冪敤鏇村ソ锛岀粨鏉熶篃鍙兘鏄敊璇粨鏉� - try { - String classPath = ResourceUtils.getURL("classpath:").getPath(); - // 鍏煎鎵撳寘涓簀ar鐨刢lass璺緞 - if(classPath.contains("jar")) { - classPath = classPath.substring(0, classPath.lastIndexOf(".")); - classPath = classPath.substring(0, classPath.lastIndexOf("/") + 1); + String path = "snap"; + String fileName = deviceId + "_" + channelId + ".jpg"; + ResponseEntity responseEntity = (ResponseEntity)result.getResult(); + if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) { + WVPResult wvpResult = (WVPResult)responseEntity.getBody(); + if (Objects.requireNonNull(wvpResult).getCode() == 0) { + StreamInfo streamInfoForSuccess = (StreamInfo)wvpResult.getData(); + MediaServerItem mediaInfo = mediaServerService.getOne(streamInfoForSuccess.getMediaServerId()); + String streamUrl = streamInfoForSuccess.getFmp4(); + // 璇锋眰鎴浘 + logger.info("[璇锋眰鎴浘]: " + fileName); + zlmresTfulUtils.getSnap(mediaInfo, streamUrl, 15, 1, path, fileName); } - if (classPath.startsWith("file:")) { - classPath = classPath.substring(classPath.indexOf(":") + 1); - } - String path = classPath + "static/static/snap/"; - // 鍏煎Windows绯荤粺璺緞锛堝幓闄ゅ墠闈㈢殑鈥�/鈥濓級 - if(System.getProperty("os.name").contains("indows")) { - path = path.substring(1); - } - String fileName = deviceId + "_" + channelId + ".jpg"; - ResponseEntity responseEntity = (ResponseEntity)result.getResult(); - if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) { - WVPResult wvpResult = (WVPResult)responseEntity.getBody(); - if (Objects.requireNonNull(wvpResult).getCode() == 0) { - StreamInfo streamInfoForSuccess = (StreamInfo)wvpResult.getData(); - MediaServerItem mediaInfo = mediaServerService.getOne(streamInfoForSuccess.getMediaServerId()); - String streamUrl = streamInfoForSuccess.getFmp4(); - // 璇锋眰鎴浘 - logger.info("[璇锋眰鎴浘]: " + fileName); - zlmresTfulUtils.getSnap(mediaInfo, streamUrl, 15, 1, path, fileName); - } - } - } catch (FileNotFoundException e) { - e.printStackTrace(); } }); if (streamInfo != null) { @@ -175,31 +171,37 @@ MediaServerItem mediaInfo = mediaServerService.getOne(mediaServerId); JSONObject rtpInfo = zlmresTfulUtils.getRtpInfo(mediaInfo, streamId); - if (rtpInfo != null && rtpInfo.getBoolean("exist")) { + if(rtpInfo.getInteger("code") == 0){ + if (rtpInfo.getBoolean("exist")) { - WVPResult wvpResult = new WVPResult(); - wvpResult.setCode(0); - wvpResult.setMsg("success"); - wvpResult.setData(streamInfo); - msg.setData(wvpResult); + WVPResult wvpResult = new WVPResult(); + wvpResult.setCode(0); + wvpResult.setMsg("success"); + wvpResult.setData(streamInfo); + msg.setData(wvpResult); - resultHolder.invokeAllResult(msg); - if (hookEvent != null) { - hookEvent.response(mediaServerItem, JSONObject.parseObject(JSON.toJSONString(streamInfo))); + resultHolder.invokeAllResult(msg); + if (hookEvent != null) { + hookEvent.response(mediaServerItem, JSONObject.parseObject(JSON.toJSONString(streamInfo))); + } + }else { + redisCatchStorage.stopPlay(streamInfo); + storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId()); + streamInfo = null; } }else { + //zlm杩炴帴澶辫触 redisCatchStorage.stopPlay(streamInfo); storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId()); streamInfo = null; } - } if (streamInfo == null) { String streamId = null; if (mediaServerItem.isRtpEnable()) { streamId = String.format("%s_%s", device.getDeviceId(), channelId); } - SSRCInfo ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, device.isSsrcCheck()); + SSRCInfo ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, device.isSsrcCheck(), false); play(mediaServerItem, ssrcInfo, device, channelId, (mediaServerItemInUse, response)->{ if (hookEvent != null) { hookEvent.response(mediaServerItem, response); @@ -243,34 +245,43 @@ streamId = String.format("%s_%s", device.getDeviceId(), channelId); } if (ssrcInfo == null) { - ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, device.isSsrcCheck()); + ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, device.isSsrcCheck(), false); } - + logger.info("[鐐规挱寮�濮媇 deviceId: {}, channelId: {}, SSRC: {}", device.getDeviceId(), channelId, ssrcInfo.getSsrc() ); // 瓒呮椂澶勭悊 String timeOutTaskKey = UUID.randomUUID().toString(); SSRCInfo finalSsrcInfo = ssrcInfo; dynamicTask.startDelay( timeOutTaskKey,()->{ - logger.warn(String.format("璁惧鐐规挱瓒呮椂锛宒eviceId锛�%s 锛宑hannelId锛�%s", device.getDeviceId(), channelId)); SIPDialog dialog = streamSession.getDialogByStream(device.getDeviceId(), channelId, finalSsrcInfo.getStream()); if (dialog != null) { + logger.info("[鐐规挱瓒呮椂] 鏀舵祦瓒呮椂 deviceId: {}, channelId: {}", device.getDeviceId(), channelId); timeoutCallback.run(1, "鏀舵祦瓒呮椂"); // 鐐规挱瓒呮椂鍥炲BYE 鍚屾椂閲婃斁ssrc浠ュ強姝ゆ鐐规挱鐨勮祫婧� cmder.streamByeCmd(device.getDeviceId(), channelId, finalSsrcInfo.getStream(), null); }else { + logger.info("[鐐规挱瓒呮椂] 娑堟伅鏈搷搴� deviceId: {}, channelId: {}", device.getDeviceId(), channelId); timeoutCallback.run(0, "鐐规挱瓒呮椂"); mediaServerService.releaseSsrc(mediaServerItem.getId(), finalSsrcInfo.getSsrc()); mediaServerService.closeRTPServer(device.getDeviceId(), channelId, finalSsrcInfo.getStream()); streamSession.remove(device.getDeviceId(), channelId, finalSsrcInfo.getStream()); } - }, userSetting.getPlayTimeout()*1000); + }, userSetting.getPlayTimeout()); final String ssrc = ssrcInfo.getSsrc(); + final String stream = ssrcInfo.getStream(); + //绔彛鑾峰彇澶辫触鐨剆srcInfo 娌℃湁蹇呰鍙戦�佺偣鎾寚浠� + if(ssrcInfo.getPort() <= 0){ + logger.info("[鐐规挱绔彛鍒嗛厤寮傚父]锛宒eviceId={},channelId={},ssrcInfo={}", device.getDeviceId(), channelId, ssrcInfo); + return; + } cmder.playStreamCmd(mediaServerItem, ssrcInfo, device, channelId, (MediaServerItem mediaServerItemInuse, JSONObject response) -> { logger.info("鏀跺埌璁㈤槄娑堟伅锛� " + response.toJSONString()); dynamicTask.stop(timeOutTaskKey); // hook鍝嶅簲 onPublishHandlerForPlay(mediaServerItemInuse, response, device.getDeviceId(), channelId, uuid); hookEvent.response(mediaServerItemInuse, response); + logger.info("[鐐规挱鎴愬姛] deviceId: {}, channelId: {}", device.getDeviceId(), channelId); + }, (event) -> { ResponseEvent responseEvent = (ResponseEvent)event.event; String contentString = new String(responseEvent.getResponse().getRawContent()); @@ -280,9 +291,15 @@ if (ssrcIndex >= 0) { //ssrc瑙勫畾闀垮害涓�10瀛楄妭锛屼笉鍙栦綑涓嬮暱搴︿互閬垮厤鍚庣画杩樻湁鈥渇=鈥濆瓧娈� TODO 鍚庣画瀵逛笉瑙勮寖鐨勯潪10浣峴src鍏煎 String ssrcInResponse = contentString.substring(ssrcIndex + 2, ssrcIndex + 12); - if (!ssrc.equals(ssrcInResponse) && device.isSsrcCheck()) { // 鏌ヨ鍒皊src涓嶄竴鑷翠笖寮�鍚簡ssrc鏍¢獙鍒欓渶瑕侀拡瀵瑰鐞� - // 鏌ヨ ssrcInResponse 鏄惁鍙敤 - if (mediaServerItem.isRtpEnable() && !mediaServerItem.getSsrcConfig().checkSsrc(ssrcInResponse)) { + // 鏌ヨ鍒皊src涓嶄竴鑷翠笖寮�鍚簡ssrc鏍¢獙鍒欓渶瑕侀拡瀵瑰鐞� + if (ssrc.equals(ssrcInResponse)) { + return; + } + logger.info("[鐐规挱娑堟伅] 鏀跺埌invite 200, 鍙戠幇涓嬬骇鑷畾涔変簡ssrc: {}", ssrcInResponse ); + if (!mediaServerItem.isRtpEnable() || device.isSsrcCheck()) { + logger.info("[SIP 娑堟伅] SSRC淇 {}->{}", ssrc, ssrcInResponse); + + if (!mediaServerItem.getSsrcConfig().checkSsrc(ssrcInResponse)) { // ssrc 涓嶅彲鐢� // 閲婃斁ssrc mediaServerService.releaseSsrc(mediaServerItem.getId(), finalSsrcInfo.getSsrc()); @@ -292,10 +309,32 @@ errorEvent.response(event); return; } + + // 鍗曠鍙fā寮弒treamId涔熸湁鍙樺寲锛岄渶瑕侀噸鏂拌缃洃鍚� + if (!mediaServerItem.isRtpEnable()) { + // 娣诲姞璁㈤槄 + JSONObject subscribeKey = new JSONObject(); + subscribeKey.put("app", "rtp"); + subscribeKey.put("stream", stream); + subscribeKey.put("regist", true); + subscribeKey.put("schema", "rtmp"); + subscribeKey.put("mediaServerId", mediaServerItem.getId()); + subscribe.removeSubscribe(ZLMHttpHookSubscribe.HookType.on_stream_changed,subscribeKey); + subscribeKey.put("stream", String.format("%08x", Integer.parseInt(ssrcInResponse)).toUpperCase()); + subscribe.addSubscribe(ZLMHttpHookSubscribe.HookType.on_stream_changed, subscribeKey, + (MediaServerItem mediaServerItemInUse, JSONObject response)->{ + logger.info("[ZLM HOOK] ssrc淇鍚庢敹鍒拌闃呮秷鎭細 " + response.toJSONString()); + dynamicTask.stop(timeOutTaskKey); + // hook鍝嶅簲 + onPublishHandlerForPlay(mediaServerItemInUse, response, device.getDeviceId(), channelId, uuid); + hookEvent.response(mediaServerItemInUse, response); + }); + } // 鍏抽棴rtp server mediaServerService.closeRTPServer(device.getDeviceId(), channelId, finalSsrcInfo.getStream()); // 閲嶆柊寮�鍚痵src server mediaServerService.openRTPServer(mediaServerItem, finalSsrcInfo.getStream(), ssrcInResponse, device.isSsrcCheck(), false); + } } }, (event) -> { @@ -366,7 +405,7 @@ return null; } MediaServerItem newMediaServerItem = getNewMediaServerItem(device); - SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, true); + SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, true, true); return playBack(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, inviteStreamCallback, callback); } @@ -412,7 +451,7 @@ cmder.streamByeCmd(device.getDeviceId(), channelId, ssrcInfo.getStream(), null); // 鍥炲涔嬪墠鎵�鏈夌殑鐐规挱璇锋眰 playBackCallback.call(playBackResult); - }, userSetting.getPlayTimeout()*1000); + }, userSetting.getPlayTimeout()); cmder.playbackStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, infoCallBack, (InviteStreamInfo inviteStreamInfo) -> { @@ -453,7 +492,7 @@ return null; } MediaServerItem newMediaServerItem = getNewMediaServerItem(device); - SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, true); + SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, true, true); return download(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, downloadSpeed,infoCallBack, hookCallBack); } @@ -501,7 +540,7 @@ cmder.streamByeCmd(device.getDeviceId(), channelId, ssrcInfo.getStream(), null); // 鍥炲涔嬪墠鎵�鏈夌殑鐐规挱璇锋眰 hookCallBack.call(downloadResult); - }, userSetting.getPlayTimeout()*1000); + }, userSetting.getPlayTimeout()); cmder.downloadStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, downloadSpeed, infoCallBack, inviteStreamInfo -> { logger.info("鏀跺埌璁㈤槄娑堟伅锛� " + inviteStreamInfo.getResponse().toJSONString()); @@ -567,7 +606,7 @@ BigDecimal currentCount = new BigDecimal(duration/1000); BigDecimal totalCount = new BigDecimal(end-start); - BigDecimal divide = currentCount.divide(totalCount,2, BigDecimal.ROUND_HALF_UP); + BigDecimal divide = currentCount.divide(totalCount,2, RoundingMode.HALF_UP); double process = divide.doubleValue(); streamInfo.setProgress(process); } @@ -641,16 +680,18 @@ } // 鏌ヨ閫氶亾浣跨敤鐘舵�� if (audioBroadcastManager.exit(device.getDeviceId(), channelId)) { - logger.warn("璇煶骞挎挱宸茬粡寮�鍚細 {}", channelId); - event.call("璇煶骞挎挱宸茬粡寮�鍚�"); - return; + SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(device.getDeviceId(), channelId, null, null); + if (sendRtpItem != null && sendRtpItem.isOnlyAudio()) { + // 鏌ヨ娴佹槸鍚﹀瓨鍦紝涓嶅瓨鍦ㄥ垯璁や负鏄紓甯哥姸鎬� + MediaServerItem mediaServerItem = mediaServerService.getOne(sendRtpItem.getMediaServerId()); + Boolean streamReady = zlmrtpServerFactory.isStreamReady(mediaServerItem, sendRtpItem.getApp(), sendRtpItem.getStreamId()); + if (streamReady) { + logger.warn("璇煶骞挎挱宸茬粡寮�鍚細 {}", channelId); + event.call("璇煶骞挎挱宸茬粡寮�鍚�"); + return; + } + } } - String timeOutTaskKey = "audio-broadcast-" + device.getDeviceId() + channelId; - dynamicTask.startDelay(timeOutTaskKey, ()->{ - logger.error("璇煶骞挎挱鍙戦�佽秴鏃讹細 {}:{}", device.getDeviceId(), channelId); - event.call("璇煶骞挎挱鍙戦�佽秴鏃�"); - audioBroadcastManager.del(device.getDeviceId(), channelId); - }, timeout * 1000); // 鍙戦�侀�氱煡 cmder.audioBroadcastCmd(device, channelId, eventResultForOk -> { @@ -658,11 +699,47 @@ AudioBroadcastCatch audioBroadcastCatch = new AudioBroadcastCatch(device.getDeviceId(), channelId, AudioBroadcastCatchStatus.Ready); audioBroadcastManager.add(audioBroadcastCatch); }, eventResultForError -> { - dynamicTask.stop(timeOutTaskKey); // 鍙戦�佸け璐� logger.error("璇煶骞挎挱鍙戦�佸け璐ワ細 {}:{}", channelId, eventResultForError.msg); event.call("璇煶骞挎挱鍙戦�佸け璐�"); - audioBroadcastManager.del(device.getDeviceId(), channelId); + stopAudioBroadcast(device.getDeviceId(), channelId); }); } + + @Override + public void stopAudioBroadcast(String deviceId, String channelId){ + AudioBroadcastCatch audioBroadcastCatch = audioBroadcastManager.get(deviceId, channelId); + if (audioBroadcastCatch != null) { + audioBroadcastManager.del(deviceId, audioBroadcastCatch.getChannelId()); + try { + SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(deviceId, audioBroadcastCatch.getChannelId(), null, null); + if (sendRtpItem != null) { + redisCatchStorage.deleteSendRTPServer(deviceId, sendRtpItem.getChannelId(), null, null); + MediaServerItem mediaInfo = mediaServerService.getOne(sendRtpItem.getMediaServerId()); + Map<String, Object> param = new HashMap<>(); + param.put("vhost", "__defaultVhost__"); + param.put("app", sendRtpItem.getApp()); + param.put("stream", sendRtpItem.getStreamId()); + zlmresTfulUtils.stopSendRtp(mediaInfo, param); + // 绔嬪埢缁撴潫璁惧鐨勬帹娴侊紝绛夊緟鑷缁撴潫澶參 +// zlmresTfulUtils.closeStreams(mediaInfo, sendRtpItem.getApp(), sendRtpItem.getStreamId()); + } + if (audioBroadcastCatch.getStatus() == AudioBroadcastCatchStatus.Ok) { + cmder.streamByeCmd(audioBroadcastCatch.getDialog(), audioBroadcastCatch.getRequest(), null); + } + + } catch (SipException e) { + throw new RuntimeException(e); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + + } + + @Override + public void zlmServerOnline(String mediaServerId) { + // 浼间箮娌″暐闇�瑕佸仛鐨� + } } -- Gitblit v1.8.0