PlayServiceImpl.java 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. package com.genersoft.iot.vmp.service.impl;
  2. import com.alibaba.fastjson2.JSONObject;
  3. import com.genersoft.iot.vmp.common.InviteInfo;
  4. import com.genersoft.iot.vmp.common.InviteSessionStatus;
  5. import com.genersoft.iot.vmp.common.InviteSessionType;
  6. import com.genersoft.iot.vmp.common.StreamInfo;
  7. import com.genersoft.iot.vmp.conf.DynamicTask;
  8. import com.genersoft.iot.vmp.conf.UserSetting;
  9. import com.genersoft.iot.vmp.conf.exception.ControllerException;
  10. import com.genersoft.iot.vmp.conf.exception.ServiceException;
  11. import com.genersoft.iot.vmp.conf.exception.SsrcTransactionNotFoundException;
  12. import com.genersoft.iot.vmp.gb28181.bean.*;
  13. import com.genersoft.iot.vmp.gb28181.event.SipSubscribe;
  14. import com.genersoft.iot.vmp.gb28181.session.VideoStreamSessionManager;
  15. import com.genersoft.iot.vmp.gb28181.transmit.callback.DeferredResultHolder;
  16. import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
  17. import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommanderFroPlatform;
  18. import com.genersoft.iot.vmp.gb28181.utils.SipUtils;
  19. import com.genersoft.iot.vmp.media.zlm.AssistRESTfulUtils;
  20. import com.genersoft.iot.vmp.media.zlm.ZLMRESTfulUtils;
  21. import com.genersoft.iot.vmp.media.zlm.ZLMServerFactory;
  22. import com.genersoft.iot.vmp.media.zlm.ZlmHttpHookSubscribe;
  23. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeFactory;
  24. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeForStreamChange;
  25. import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem;
  26. import com.genersoft.iot.vmp.media.zlm.dto.hook.HookParam;
  27. import com.genersoft.iot.vmp.media.zlm.dto.hook.OnStreamChangedHookParam;
  28. import com.genersoft.iot.vmp.service.*;
  29. import com.genersoft.iot.vmp.service.bean.ErrorCallback;
  30. import com.genersoft.iot.vmp.service.bean.InviteErrorCode;
  31. import com.genersoft.iot.vmp.service.bean.SSRCInfo;
  32. import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
  33. import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
  34. import com.genersoft.iot.vmp.utils.DateUtil;
  35. import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
  36. import gov.nist.javax.sip.message.SIPResponse;
  37. import org.slf4j.Logger;
  38. import org.slf4j.LoggerFactory;
  39. import org.springframework.beans.factory.annotation.Autowired;
  40. import org.springframework.stereotype.Service;
  41. import org.springframework.util.ObjectUtils;
  42. import javax.sdp.*;
  43. import javax.sip.InvalidArgumentException;
  44. import javax.sip.ResponseEvent;
  45. import javax.sip.SipException;
  46. import java.io.File;
  47. import java.math.BigDecimal;
  48. import java.math.RoundingMode;
  49. import java.text.ParseException;
  50. import java.util.List;
  51. import java.util.UUID;
  52. import java.util.Vector;
  53. @SuppressWarnings(value = {"rawtypes", "unchecked"})
  54. @Service
  55. public class PlayServiceImpl implements IPlayService {
  56. private final static Logger logger = LoggerFactory.getLogger(PlayServiceImpl.class);
  57. @Autowired
  58. private IVideoManagerStorage storager;
  59. @Autowired
  60. private SIPCommander cmder;
  61. @Autowired
  62. private SIPCommanderFroPlatform sipCommanderFroPlatform;
  63. @Autowired
  64. private IRedisCatchStorage redisCatchStorage;
  65. @Autowired
  66. private IInviteStreamService inviteStreamService;
  67. @Autowired
  68. private DeferredResultHolder resultHolder;
  69. @Autowired
  70. private ZLMRESTfulUtils zlmresTfulUtils;
  71. @Autowired
  72. private ZLMServerFactory zlmServerFactory;
  73. @Autowired
  74. private AssistRESTfulUtils assistRESTfulUtils;
  75. @Autowired
  76. private IMediaService mediaService;
  77. @Autowired
  78. private IMediaServerService mediaServerService;
  79. @Autowired
  80. private VideoStreamSessionManager streamSession;
  81. @Autowired
  82. private IDeviceService deviceService;
  83. @Autowired
  84. private UserSetting userSetting;
  85. @Autowired
  86. private DynamicTask dynamicTask;
  87. @Autowired
  88. private ZlmHttpHookSubscribe subscribe;
  89. @Override
  90. public SSRCInfo play(MediaServerItem mediaServerItem, String deviceId, String channelId, String ssrc, ErrorCallback<Object> callback) {
  91. if (mediaServerItem == null) {
  92. logger.warn("[点播] 未找到可用的zlm deviceId: {},channelId:{}", deviceId, channelId);
  93. throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到可用的zlm");
  94. }
  95. Device device = redisCatchStorage.getDevice(deviceId);
  96. if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE") && !mediaServerItem.isRtpEnable()) {
  97. logger.warn("[点播] 单端口收流时不支持TCP主动方式收流 deviceId: {},channelId:{}", deviceId, channelId);
  98. throw new ControllerException(ErrorCode.ERROR100.getCode(), "单端口收流时不支持TCP主动方式收流");
  99. }
  100. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  101. if (inviteInfo != null ) {
  102. if (inviteInfo.getStreamInfo() == null) {
  103. // 点播发起了但是尚未成功, 仅注册回调等待结果即可
  104. inviteStreamService.once(InviteSessionType.PLAY, deviceId, channelId, null, callback);
  105. logger.info("[点播开始] 已经请求中,等待结果, deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
  106. return inviteInfo.getSsrcInfo();
  107. }else {
  108. StreamInfo streamInfo = inviteInfo.getStreamInfo();
  109. String streamId = streamInfo.getStream();
  110. if (streamId == null) {
  111. callback.run(InviteErrorCode.ERROR_FOR_CATCH_DATA.getCode(), "点播失败, redis缓存streamId等于null", null);
  112. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  113. InviteErrorCode.ERROR_FOR_CATCH_DATA.getCode(),
  114. "点播失败, redis缓存streamId等于null",
  115. null);
  116. return inviteInfo.getSsrcInfo();
  117. }
  118. String mediaServerId = streamInfo.getMediaServerId();
  119. MediaServerItem mediaInfo = mediaServerService.getOne(mediaServerId);
  120. Boolean ready = zlmServerFactory.isStreamReady(mediaInfo, "rtp", streamId);
  121. if (ready != null && ready) {
  122. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  123. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  124. InviteErrorCode.SUCCESS.getCode(),
  125. InviteErrorCode.SUCCESS.getMsg(),
  126. streamInfo);
  127. logger.info("[点播已存在] 直接返回, deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
  128. return inviteInfo.getSsrcInfo();
  129. }else {
  130. // 点播发起了但是尚未成功, 仅注册回调等待结果即可
  131. inviteStreamService.once(InviteSessionType.PLAY, deviceId, channelId, null, callback);
  132. storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId());
  133. inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  134. }
  135. }
  136. }
  137. String streamId = null;
  138. if (mediaServerItem.isRtpEnable()) {
  139. streamId = String.format("%s_%s", device.getDeviceId(), channelId);
  140. }
  141. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, ssrc, device.isSsrcCheck(), false, 0, false, device.getStreamModeForParam());
  142. if (ssrcInfo == null) {
  143. callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getMsg(), null);
  144. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  145. InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(),
  146. InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getMsg(),
  147. null);
  148. return null;
  149. }
  150. play(mediaServerItem, ssrcInfo, device, channelId, callback);
  151. return ssrcInfo;
  152. }
  153. @Override
  154. public void play(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo, Device device, String channelId,
  155. ErrorCallback<Object> callback) {
  156. if (mediaServerItem == null || ssrcInfo == null) {
  157. callback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(),
  158. InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getMsg(),
  159. null);
  160. return;
  161. }
  162. logger.info("[点播开始] deviceId: {}, channelId: {},码流类型:{}, 收流端口: {}, STREAM:{}, 收流模式:{}, SSRC: {}, SSRC校验:{}",
  163. device.getDeviceId(), channelId, device.isSwitchPrimarySubStream() ? "辅码流" : "主码流", ssrcInfo.getPort(), ssrcInfo.getStream(),
  164. device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
  165. //端口获取失败的ssrcInfo 没有必要发送点播指令
  166. if (ssrcInfo.getPort() <= 0) {
  167. logger.info("[点播端口分配异常],deviceId={},channelId={},ssrcInfo={}", device.getDeviceId(), channelId, ssrcInfo);
  168. // 释放ssrc
  169. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  170. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  171. callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "点播端口分配异常", null);
  172. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  173. InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "点播端口分配异常", null);
  174. return;
  175. }
  176. // 初始化redis中的invite消息状态
  177. InviteInfo inviteInfo = InviteInfo.getInviteInfo(device.getDeviceId(), channelId, ssrcInfo.getStream(), ssrcInfo,
  178. mediaServerItem.getSdpIp(), ssrcInfo.getPort(), device.getStreamMode(), InviteSessionType.PLAY,
  179. InviteSessionStatus.ready);
  180. inviteInfo.setSubStream(device.isSwitchPrimarySubStream());
  181. inviteStreamService.updateInviteInfo(inviteInfo);
  182. // 超时处理
  183. String timeOutTaskKey = UUID.randomUUID().toString();
  184. dynamicTask.startDelay(timeOutTaskKey, () -> {
  185. // 执行超时任务时查询是否已经成功,成功了则不执行超时任务,防止超时任务取消失败的情况
  186. InviteInfo inviteInfoForTimeOut = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getDeviceId(), channelId);
  187. if (inviteInfoForTimeOut == null || inviteInfoForTimeOut.getStreamInfo() == null) {
  188. logger.info("[点播超时] 收流超时 deviceId: {}, channelId: {},码流类型:{},端口:{}, SSRC: {}",
  189. device.getDeviceId(), channelId, device.isSwitchPrimarySubStream() ? "辅码流" : "主码流",
  190. ssrcInfo.getPort(), ssrcInfo.getSsrc());
  191. callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), null);
  192. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  193. InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), null);
  194. inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getDeviceId(), channelId);
  195. try {
  196. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
  197. } catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) {
  198. logger.error("[点播超时], 发送BYE失败 {}", e.getMessage());
  199. } finally {
  200. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  201. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  202. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  203. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  204. // 取消订阅消息监听
  205. HookSubscribeForStreamChange hookSubscribe = HookSubscribeFactory.on_stream_changed("rtp", ssrcInfo.getStream(), true, "rtsp", mediaServerItem.getId());
  206. subscribe.removeSubscribe(hookSubscribe);
  207. }
  208. }
  209. }, userSetting.getPlayTimeout());
  210. try {
  211. cmder.playStreamCmd(mediaServerItem, ssrcInfo, device, channelId, (mediaServerItemInuse, hookParam ) -> {
  212. logger.info("收到订阅消息: " + hookParam);
  213. dynamicTask.stop(timeOutTaskKey);
  214. // hook响应
  215. StreamInfo streamInfo = onPublishHandlerForPlay(mediaServerItemInuse, hookParam, device.getDeviceId(), channelId);
  216. if (streamInfo == null){
  217. callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  218. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  219. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  220. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  221. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  222. return;
  223. }
  224. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  225. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  226. InviteErrorCode.SUCCESS.getCode(),
  227. InviteErrorCode.SUCCESS.getMsg(),
  228. streamInfo);
  229. logger.info("[点播成功] deviceId: {}, channelId:{}, 码流类型:{}", device.getDeviceId(), channelId,
  230. device.isSwitchPrimarySubStream() ? "辅码流" : "主码流");
  231. snapOnPlay(mediaServerItemInuse, device.getDeviceId(), channelId, ssrcInfo.getStream());
  232. }, (eventResult) -> {
  233. // 处理收到200ok后的TCP主动连接以及SSRC不一致的问题
  234. InviteOKHandler(eventResult, ssrcInfo, mediaServerItem, device, channelId,
  235. timeOutTaskKey, callback, inviteInfo, InviteSessionType.PLAY);
  236. }, (event) -> {
  237. dynamicTask.stop(timeOutTaskKey);
  238. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  239. // 释放ssrc
  240. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  241. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  242. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_ERROR.getCode(),
  243. String.format("点播失败, 错误码: %s, %s", event.statusCode, event.msg), null);
  244. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  245. InviteErrorCode.ERROR_FOR_RESET_SSRC.getCode(),
  246. String.format("点播失败, 错误码: %s, %s", event.statusCode, event.msg), null);
  247. inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getDeviceId(), channelId);
  248. });
  249. } catch (InvalidArgumentException | SipException | ParseException e) {
  250. logger.error("[命令发送失败] 点播消息: {}", e.getMessage());
  251. dynamicTask.stop(timeOutTaskKey);
  252. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  253. // 释放ssrc
  254. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  255. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  256. callback.run(InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getCode(),
  257. InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getMsg(), null);
  258. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  259. InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getCode(),
  260. InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getMsg(), null);
  261. inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getDeviceId(), channelId);
  262. }
  263. }
  264. private void tcpActiveHandler(Device device, String channelId, String contentString,
  265. MediaServerItem mediaServerItem,
  266. String timeOutTaskKey, SSRCInfo ssrcInfo, ErrorCallback<Object> callback){
  267. if (!device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE")) {
  268. return;
  269. }
  270. String substring = contentString.substring(0, contentString.indexOf("y="));
  271. try {
  272. SessionDescription sdp = SdpFactory.getInstance().createSessionDescription(substring);
  273. int port = -1;
  274. Vector mediaDescriptions = sdp.getMediaDescriptions(true);
  275. for (Object description : mediaDescriptions) {
  276. MediaDescription mediaDescription = (MediaDescription) description;
  277. Media media = mediaDescription.getMedia();
  278. Vector mediaFormats = media.getMediaFormats(false);
  279. if (mediaFormats.contains("96")) {
  280. port = media.getMediaPort();
  281. break;
  282. }
  283. }
  284. logger.info("[TCP主动连接对方] deviceId: {}, channelId: {}, 连接对方的地址:{}:{}, 收流模式:{}, SSRC: {}, SSRC校验:{}", device.getDeviceId(), channelId, sdp.getConnection().getAddress(), port, device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
  285. JSONObject jsonObject = zlmresTfulUtils.connectRtpServer(mediaServerItem, sdp.getConnection().getAddress(), port, ssrcInfo.getStream());
  286. logger.info("[TCP主动连接对方] 结果: {}", jsonObject);
  287. } catch (SdpException e) {
  288. logger.error("[TCP主动连接对方] deviceId: {}, channelId: {}, 解析200OK的SDP信息失败", device.getDeviceId(), channelId, e);
  289. dynamicTask.stop(timeOutTaskKey);
  290. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  291. // 释放ssrc
  292. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  293. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  294. callback.run(InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getCode(),
  295. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getMsg(), null);
  296. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  297. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getCode(),
  298. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getMsg(), null);
  299. }
  300. }
  301. /**
  302. * 点播成功时调用截图.
  303. *
  304. * @param mediaServerItemInuse media
  305. * @param deviceId 设备 ID
  306. * @param channelId 通道 ID
  307. * @param stream ssrc
  308. */
  309. private void snapOnPlay(MediaServerItem mediaServerItemInuse, String deviceId, String channelId, String stream) {
  310. String streamUrl;
  311. if (mediaServerItemInuse.getRtspPort() != 0) {
  312. streamUrl = String.format("rtsp://127.0.0.1:%s/%s/%s", mediaServerItemInuse.getRtspPort(), "rtp", stream);
  313. } else {
  314. streamUrl = String.format("http://127.0.0.1:%s/%s/%s.live.mp4", mediaServerItemInuse.getHttpPort(), "rtp", stream);
  315. }
  316. String path = "snap";
  317. String fileName = deviceId + "_" + channelId + ".jpg";
  318. // 请求截图
  319. logger.info("[请求截图]: " + fileName);
  320. zlmresTfulUtils.getSnap(mediaServerItemInuse, streamUrl, 15, 1, path, fileName);
  321. }
  322. private StreamInfo onPublishHandlerForPlay(MediaServerItem mediaServerItem, HookParam hookParam, String deviceId, String channelId) {
  323. StreamInfo streamInfo = null;
  324. Device device = redisCatchStorage.getDevice(deviceId);
  325. OnStreamChangedHookParam streamChangedHookParam = (OnStreamChangedHookParam)hookParam;
  326. streamInfo = onPublishHandler(mediaServerItem, streamChangedHookParam, deviceId, channelId);
  327. if (streamInfo != null) {
  328. DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
  329. if (deviceChannel != null) {
  330. deviceChannel.setStreamId(streamInfo.getStream());
  331. storager.startPlay(deviceId, channelId, streamInfo.getStream());
  332. }
  333. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  334. if (inviteInfo != null) {
  335. inviteInfo.setStatus(InviteSessionStatus.ok);
  336. inviteInfo.setStreamInfo(streamInfo);
  337. inviteStreamService.updateInviteInfo(inviteInfo);
  338. }
  339. }
  340. return streamInfo;
  341. }
  342. private StreamInfo onPublishHandlerForPlayback(MediaServerItem mediaServerItem, HookParam param, String deviceId, String channelId, String startTime, String endTime) {
  343. OnStreamChangedHookParam streamChangedHookParam = (OnStreamChangedHookParam) param;
  344. StreamInfo streamInfo = onPublishHandler(mediaServerItem, streamChangedHookParam, deviceId, channelId);
  345. if (streamInfo != null) {
  346. streamInfo.setStartTime(startTime);
  347. streamInfo.setEndTime(endTime);
  348. DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
  349. if (deviceChannel != null) {
  350. deviceChannel.setStreamId(streamInfo.getStream());
  351. storager.startPlay(deviceId, channelId, streamInfo.getStream());
  352. }
  353. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAYBACK, deviceId, channelId);
  354. if (inviteInfo != null) {
  355. inviteInfo.setStatus(InviteSessionStatus.ok);
  356. inviteInfo.setStreamInfo(streamInfo);
  357. inviteStreamService.updateInviteInfo(inviteInfo);
  358. }
  359. }
  360. return streamInfo;
  361. }
  362. @Override
  363. public MediaServerItem getNewMediaServerItem(Device device) {
  364. if (device == null) {
  365. return null;
  366. }
  367. MediaServerItem mediaServerItem;
  368. if (ObjectUtils.isEmpty(device.getMediaServerId()) || "auto".equals(device.getMediaServerId())) {
  369. mediaServerItem = mediaServerService.getMediaServerForMinimumLoad(null);
  370. } else {
  371. mediaServerItem = mediaServerService.getOne(device.getMediaServerId());
  372. }
  373. if (mediaServerItem == null) {
  374. logger.warn("点播时未找到可使用的ZLM...");
  375. }
  376. return mediaServerItem;
  377. }
  378. @Override
  379. public MediaServerItem getNewMediaServerItemHasAssist(Device device) {
  380. if (device == null) {
  381. return null;
  382. }
  383. MediaServerItem mediaServerItem;
  384. if (ObjectUtils.isEmpty(device.getMediaServerId()) || "auto".equals(device.getMediaServerId())) {
  385. mediaServerItem = mediaServerService.getMediaServerForMinimumLoad(true);
  386. } else {
  387. mediaServerItem = mediaServerService.getOne(device.getMediaServerId());
  388. }
  389. if (mediaServerItem == null) {
  390. logger.warn("[获取可用的ZLM节点]未找到可使用的ZLM...");
  391. }
  392. return mediaServerItem;
  393. }
  394. @Override
  395. public void playBack(String deviceId, String channelId, String startTime,
  396. String endTime, ErrorCallback<Object> callback) {
  397. Device device = storager.queryVideoDevice(deviceId);
  398. if (device == null) {
  399. logger.warn("[录像回放] 未找到设备 deviceId: {},channelId:{}", deviceId, channelId);
  400. throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到设备:" + deviceId);
  401. }
  402. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  403. if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE") && ! newMediaServerItem.isRtpEnable()) {
  404. logger.warn("[录像回放] 单端口收流时不支持TCP主动方式收流 deviceId: {},channelId:{}", deviceId, channelId);
  405. throw new ControllerException(ErrorCode.ERROR100.getCode(), "单端口收流时不支持TCP主动方式收流");
  406. }
  407. String stream = null;
  408. if (newMediaServerItem.isRtpEnable()) {
  409. String startTimeStr = startTime.replace("-", "")
  410. .replace(":", "")
  411. .replace(" ", "");
  412. String endTimeTimeStr = endTime.replace("-", "")
  413. .replace(":", "")
  414. .replace(" ", "");
  415. stream = deviceId + "_" + channelId + "_" + startTimeStr + "_" + endTimeTimeStr;
  416. }
  417. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, stream, null, device.isSsrcCheck(), true, 0, false, device.getStreamModeForParam());
  418. playBack(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, callback);
  419. }
  420. @Override
  421. public void playBack(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo,
  422. String deviceId, String channelId, String startTime,
  423. String endTime, ErrorCallback<Object> callback) {
  424. if (mediaServerItem == null || ssrcInfo == null) {
  425. callback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(),
  426. InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getMsg(),
  427. null);
  428. return;
  429. }
  430. Device device = storager.queryVideoDevice(deviceId);
  431. if (device == null) {
  432. throw new ControllerException(ErrorCode.ERROR100.getCode(), "设备: " + deviceId + "不存在");
  433. }
  434. logger.info("[录像回放] deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}, 收流端口:{}, 收流模式:{}, SSRC: {}, SSRC校验:{}",
  435. device.getDeviceId(), channelId, startTime, endTime, ssrcInfo.getPort(), device.getStreamMode(),
  436. ssrcInfo.getSsrc(), device.isSsrcCheck());
  437. // 初始化redis中的invite消息状态
  438. InviteInfo inviteInfo = InviteInfo.getInviteInfo(device.getDeviceId(), channelId, ssrcInfo.getStream(), ssrcInfo,
  439. mediaServerItem.getSdpIp(), ssrcInfo.getPort(), device.getStreamMode(), InviteSessionType.PLAYBACK,
  440. InviteSessionStatus.ready);
  441. inviteStreamService.updateInviteInfo(inviteInfo);
  442. String playBackTimeOutTaskKey = UUID.randomUUID().toString();
  443. dynamicTask.startDelay(playBackTimeOutTaskKey, () -> {
  444. logger.warn("[录像回放] 超时,deviceId:{} ,channelId:{}", deviceId, channelId);
  445. inviteStreamService.removeInviteInfo(inviteInfo);
  446. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getMsg(), null);
  447. try {
  448. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
  449. } catch (InvalidArgumentException | ParseException | SipException e) {
  450. logger.error("[录像回放] 超时 发送BYE失败 {}", e.getMessage());
  451. } catch (SsrcTransactionNotFoundException e) {
  452. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  453. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  454. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  455. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  456. }
  457. }, userSetting.getPlayTimeout());
  458. SipSubscribe.Event errorEvent = event -> {
  459. logger.info("[录像回放] 失败,{} {}", event.statusCode, event.msg);
  460. dynamicTask.stop(playBackTimeOutTaskKey);
  461. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_ERROR.getCode(),
  462. String.format("回放失败, 错误码: %s, %s", event.statusCode, event.msg), null);
  463. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  464. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  465. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  466. inviteStreamService.removeInviteInfo(inviteInfo);
  467. };
  468. ZlmHttpHookSubscribe.Event hookEvent = (mediaServerItemInuse, hookParam) -> {
  469. logger.info("收到回放订阅消息: " + hookParam);
  470. dynamicTask.stop(playBackTimeOutTaskKey);
  471. StreamInfo streamInfo = onPublishHandlerForPlayback(mediaServerItemInuse, hookParam, deviceId, channelId, startTime, endTime);
  472. if (streamInfo == null) {
  473. logger.warn("设备回放API调用失败!");
  474. callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  475. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  476. return;
  477. }
  478. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  479. logger.info("[录像回放] 成功 deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}", device.getDeviceId(), channelId, startTime, endTime);
  480. };
  481. try {
  482. cmder.playbackStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime,
  483. hookEvent, eventResult -> {
  484. // 处理收到200ok后的TCP主动连接以及SSRC不一致的问题
  485. InviteOKHandler(eventResult, ssrcInfo, mediaServerItem, device, channelId,
  486. playBackTimeOutTaskKey, callback, inviteInfo, InviteSessionType.PLAYBACK);
  487. }, errorEvent);
  488. } catch (InvalidArgumentException | SipException | ParseException e) {
  489. logger.error("[命令发送失败] 录像回放: {}", e.getMessage());
  490. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult();
  491. eventResult.type = SipSubscribe.EventResultType.cmdSendFailEvent;
  492. eventResult.statusCode = -1;
  493. eventResult.msg = "命令发送失败";
  494. errorEvent.response(eventResult);
  495. }
  496. }
  497. private void InviteOKHandler(SipSubscribe.EventResult eventResult, SSRCInfo ssrcInfo, MediaServerItem mediaServerItem,
  498. Device device, String channelId, String timeOutTaskKey, ErrorCallback<Object> callback,
  499. InviteInfo inviteInfo, InviteSessionType inviteSessionType){
  500. inviteInfo.setStatus(InviteSessionStatus.ok);
  501. ResponseEvent responseEvent = (ResponseEvent) eventResult.event;
  502. String contentString = new String(responseEvent.getResponse().getRawContent());
  503. String ssrcInResponse = SipUtils.getSsrcFromSdp(contentString);
  504. if (ssrcInfo.getSsrc().equals(ssrcInResponse)) {
  505. // ssrc 一致
  506. if (mediaServerItem.isRtpEnable()) {
  507. // 多端口
  508. if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE")) {
  509. tcpActiveHandler(device, channelId, contentString, mediaServerItem, timeOutTaskKey, ssrcInfo, callback);
  510. }
  511. }else {
  512. // 单端口
  513. if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE")) {
  514. logger.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流");
  515. }
  516. }
  517. }else {
  518. logger.info("[Invite 200OK] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse);
  519. // ssrc 不一致
  520. if (mediaServerItem.isRtpEnable()) {
  521. // 多端口
  522. if (device.isSsrcCheck()) {
  523. // ssrc检验
  524. // 更新ssrc
  525. logger.info("[Invite 200OK] SSRC修正 {}->{}", ssrcInfo.getSsrc(), ssrcInResponse);
  526. // 释放ssrc
  527. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  528. Boolean result = mediaServerService.updateRtpServerSSRC(mediaServerItem, ssrcInfo.getStream(), ssrcInResponse);
  529. if (!result) {
  530. try {
  531. logger.warn("[Invite 200OK] 更新ssrc失败,停止点播 {}/{}", device.getDeviceId(), channelId);
  532. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null, null);
  533. } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) {
  534. logger.error("[命令发送失败] 停止播放, 发送BYE: {}", e.getMessage());
  535. }
  536. dynamicTask.stop(timeOutTaskKey);
  537. // 释放ssrc
  538. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  539. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  540. callback.run(InviteErrorCode.ERROR_FOR_RESET_SSRC.getCode(),
  541. "下级自定义了ssrc,重新设置收流信息失败", null);
  542. inviteStreamService.call(inviteSessionType, device.getDeviceId(), channelId, null,
  543. InviteErrorCode.ERROR_FOR_RESET_SSRC.getCode(),
  544. "下级自定义了ssrc,重新设置收流信息失败", null);
  545. }else {
  546. ssrcInfo.setSsrc(ssrcInResponse);
  547. inviteInfo.setSsrcInfo(ssrcInfo);
  548. inviteInfo.setStream(ssrcInfo.getStream());
  549. if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE")) {
  550. if (mediaServerItem.isRtpEnable()) {
  551. tcpActiveHandler(device, channelId, contentString, mediaServerItem, timeOutTaskKey, ssrcInfo, callback);
  552. }else {
  553. logger.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流");
  554. }
  555. }
  556. inviteStreamService.updateInviteInfo(inviteInfo);
  557. }
  558. }
  559. }else {
  560. if (ssrcInResponse != null) {
  561. // 单端口
  562. // 重新订阅流上线
  563. HookSubscribeForStreamChange hookSubscribe = HookSubscribeFactory.on_stream_changed("rtp",
  564. ssrcInfo.getStream(), true, "rtsp", mediaServerItem.getId());
  565. subscribe.removeSubscribe(hookSubscribe);
  566. SsrcTransaction ssrcTransaction = streamSession.getSsrcTransaction(inviteInfo.getDeviceId(),
  567. inviteInfo.getChannelId(), null, inviteInfo.getStream());
  568. streamSession.remove(inviteInfo.getDeviceId(),
  569. inviteInfo.getChannelId(), inviteInfo.getStream());
  570. String stream = String.format("%08x", Integer.parseInt(ssrcInResponse)).toUpperCase();
  571. hookSubscribe.getContent().put("stream", stream);
  572. inviteStreamService.updateInviteInfoForStream(inviteInfo, stream);
  573. streamSession.put(device.getDeviceId(), channelId, ssrcTransaction.getCallId(),
  574. stream, ssrcInResponse, mediaServerItem.getId(), (SIPResponse) responseEvent.getResponse(), inviteSessionType);
  575. subscribe.addSubscribe(hookSubscribe, (mediaServerItemInUse, hookParam) -> {
  576. logger.info("[Invite 200OK] ssrc修正后收到订阅消息: " + hookParam);
  577. dynamicTask.stop(timeOutTaskKey);
  578. subscribe.removeSubscribe(hookSubscribe);
  579. // hook响应
  580. StreamInfo streamInfo = onPublishHandlerForPlay(mediaServerItemInUse, hookParam, device.getDeviceId(), channelId);
  581. if (streamInfo == null){
  582. callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  583. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  584. inviteStreamService.call(inviteSessionType, device.getDeviceId(), channelId, null,
  585. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  586. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  587. return;
  588. }
  589. callback.run(InviteErrorCode.SUCCESS.getCode(),
  590. InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  591. inviteStreamService.call(inviteSessionType, device.getDeviceId(), channelId, null,
  592. InviteErrorCode.SUCCESS.getCode(),
  593. InviteErrorCode.SUCCESS.getMsg(),
  594. streamInfo);
  595. if (inviteSessionType == InviteSessionType.PLAY) {
  596. snapOnPlay(mediaServerItemInUse, device.getDeviceId(), channelId, stream);
  597. }
  598. });
  599. }
  600. }
  601. }
  602. }
  603. @Override
  604. public void download(String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, ErrorCallback<Object> callback) {
  605. Device device = storager.queryVideoDevice(deviceId);
  606. if (device == null) {
  607. return;
  608. }
  609. MediaServerItem newMediaServerItem = getNewMediaServerItemHasAssist(device);
  610. if (newMediaServerItem == null) {
  611. callback.run(InviteErrorCode.ERROR_FOR_ASSIST_NOT_READY.getCode(),
  612. InviteErrorCode.ERROR_FOR_ASSIST_NOT_READY.getMsg(),
  613. null);
  614. return;
  615. }
  616. // 录像下载不使用固定流地址,固定流地址会导致如果开始时间与结束时间一致时文件错误的叠加在一起
  617. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, null, device.isSsrcCheck(), true, 0, false, device.getStreamModeForParam());
  618. download(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, downloadSpeed, callback);
  619. }
  620. @Override
  621. public void download(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo, String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, ErrorCallback<Object> callback) {
  622. if (mediaServerItem == null || ssrcInfo == null) {
  623. callback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(),
  624. InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getMsg(),
  625. null);
  626. return;
  627. }
  628. Device device = storager.queryVideoDevice(deviceId);
  629. if (device == null) {
  630. callback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(),
  631. "设备:" + deviceId + "不存在",
  632. null);
  633. return;
  634. }
  635. logger.info("[录像下载] deviceId: {}, channelId: {}, 下载速度:{}, 收流端口:{}, 收流模式:{}, SSRC: {}, SSRC校验:{}", device.getDeviceId(), channelId, downloadSpeed, ssrcInfo.getPort(), device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
  636. // 初始化redis中的invite消息状态
  637. InviteInfo inviteInfo = InviteInfo.getInviteInfo(device.getDeviceId(), channelId, ssrcInfo.getStream(), ssrcInfo,
  638. mediaServerItem.getSdpIp(), ssrcInfo.getPort(), device.getStreamMode(), InviteSessionType.DOWNLOAD,
  639. InviteSessionStatus.ready);
  640. inviteStreamService.updateInviteInfo(inviteInfo);
  641. String downLoadTimeOutTaskKey = UUID.randomUUID().toString();
  642. dynamicTask.startDelay(downLoadTimeOutTaskKey, () -> {
  643. logger.warn(String.format("录像下载请求超时,deviceId:%s ,channelId:%s", deviceId, channelId));
  644. inviteStreamService.removeInviteInfo(inviteInfo);
  645. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getCode(),
  646. InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getMsg(), null);
  647. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  648. try {
  649. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
  650. } catch (InvalidArgumentException | ParseException | SipException e) {
  651. logger.error("[录像流]录像下载请求超时, 发送BYE失败 {}", e.getMessage());
  652. } catch (SsrcTransactionNotFoundException e) {
  653. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  654. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  655. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  656. }
  657. }, userSetting.getPlayTimeout());
  658. SipSubscribe.Event errorEvent = event -> {
  659. dynamicTask.stop(downLoadTimeOutTaskKey);
  660. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getCode(),
  661. String.format("录像下载失败, 错误码: %s, %s", event.statusCode, event.msg), null);
  662. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  663. inviteStreamService.removeInviteInfo(inviteInfo);
  664. };
  665. ZlmHttpHookSubscribe.Event hookEvent = (mediaServerItemInuse, hookParam) -> {
  666. logger.info("[录像下载]收到订阅消息: " + hookParam);
  667. dynamicTask.stop(downLoadTimeOutTaskKey);
  668. StreamInfo streamInfo = onPublishHandlerForDownload(mediaServerItemInuse, hookParam, deviceId, channelId, startTime, endTime);
  669. if (streamInfo == null) {
  670. logger.warn("[录像下载] 获取流地址信息失败");
  671. callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  672. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  673. return;
  674. }
  675. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  676. logger.info("[录像下载] 调用成功 deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}", device.getDeviceId(), channelId, startTime, endTime);
  677. };
  678. try {
  679. cmder.downloadStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, downloadSpeed,
  680. hookEvent, errorEvent, eventResult ->{
  681. // 处理收到200ok后的TCP主动连接以及SSRC不一致的问题
  682. InviteOKHandler(eventResult, ssrcInfo, mediaServerItem, device, channelId,
  683. downLoadTimeOutTaskKey, callback, inviteInfo, InviteSessionType.DOWNLOAD);
  684. });
  685. } catch (InvalidArgumentException | SipException | ParseException e) {
  686. logger.error("[命令发送失败] 录像下载: {}", e.getMessage());
  687. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult();
  688. eventResult.type = SipSubscribe.EventResultType.cmdSendFailEvent;
  689. eventResult.statusCode = -1;
  690. eventResult.msg = "命令发送失败";
  691. errorEvent.response(eventResult);
  692. }
  693. }
  694. @Override
  695. public StreamInfo getDownLoadInfo(String deviceId, String channelId, String stream) {
  696. InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.DOWNLOAD, deviceId, channelId, stream);
  697. if (inviteInfo != null && inviteInfo.getStreamInfo() != null) {
  698. if (inviteInfo.getStreamInfo().getProgress() == 1) {
  699. return inviteInfo.getStreamInfo();
  700. }
  701. // 获取当前已下载时长
  702. String mediaServerId = inviteInfo.getStreamInfo().getMediaServerId();
  703. MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  704. if (mediaServerItem == null) {
  705. logger.warn("查询录像信息时发现节点已离线");
  706. return null;
  707. }
  708. if (mediaServerItem.getRecordAssistPort() > 0) {
  709. JSONObject jsonObject = assistRESTfulUtils.fileDuration(mediaServerItem, inviteInfo.getStreamInfo().getApp(), inviteInfo.getStreamInfo().getStream(), null);
  710. if (jsonObject == null) {
  711. throw new ControllerException(ErrorCode.ERROR100.getCode(), "连接Assist服务失败");
  712. }
  713. if (jsonObject.getInteger("code") == 0) {
  714. long duration = jsonObject.getLong("data");
  715. if (duration == 0) {
  716. inviteInfo.getStreamInfo().setProgress(0);
  717. } else {
  718. String startTime = inviteInfo.getStreamInfo().getStartTime();
  719. String endTime = inviteInfo.getStreamInfo().getEndTime();
  720. long start = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(startTime);
  721. long end = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(endTime);
  722. BigDecimal currentCount = new BigDecimal(duration / 1000);
  723. BigDecimal totalCount = new BigDecimal(end - start);
  724. BigDecimal divide = currentCount.divide(totalCount, 2, RoundingMode.HALF_UP);
  725. double process = divide.doubleValue();
  726. inviteInfo.getStreamInfo().setProgress(process);
  727. }
  728. inviteStreamService.updateInviteInfo(inviteInfo);
  729. }
  730. }
  731. return inviteInfo.getStreamInfo();
  732. }
  733. return null;
  734. }
  735. private StreamInfo onPublishHandlerForDownload(MediaServerItem mediaServerItemInuse, HookParam hookParam, String deviceId, String channelId, String startTime, String endTime) {
  736. OnStreamChangedHookParam streamChangedHookParam = (OnStreamChangedHookParam) hookParam;
  737. StreamInfo streamInfo = onPublishHandler(mediaServerItemInuse, streamChangedHookParam, deviceId, channelId);
  738. if (streamInfo != null) {
  739. streamInfo.setProgress(0);
  740. streamInfo.setStartTime(startTime);
  741. streamInfo.setEndTime(endTime);
  742. InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.DOWNLOAD, deviceId, channelId, streamInfo.getStream());
  743. if (inviteInfo != null) {
  744. logger.info("[录像下载] 更新invite消息中的stream信息");
  745. inviteInfo.setStatus(InviteSessionStatus.ok);
  746. inviteInfo.setStreamInfo(streamInfo);
  747. inviteStreamService.updateInviteInfo(inviteInfo);
  748. }
  749. }
  750. return streamInfo;
  751. }
  752. public StreamInfo onPublishHandler(MediaServerItem mediaServerItem, OnStreamChangedHookParam hookParam, String deviceId, String channelId) {
  753. StreamInfo streamInfo = mediaService.getStreamInfoByAppAndStream(mediaServerItem, "rtp", hookParam.getStream(), hookParam.getTracks(), null);
  754. streamInfo.setDeviceID(deviceId);
  755. streamInfo.setChannelId(channelId);
  756. return streamInfo;
  757. }
  758. @Override
  759. public void zlmServerOffline(String mediaServerId) {
  760. // 处理正在向上推流的上级平台
  761. List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  762. if (sendRtpItems.size() > 0) {
  763. for (SendRtpItem sendRtpItem : sendRtpItems) {
  764. if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  765. ParentPlatform platform = storager.queryParentPlatByServerGBId(sendRtpItem.getPlatformId());
  766. try {
  767. sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  768. } catch (SipException | InvalidArgumentException | ParseException e) {
  769. logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
  770. }
  771. }
  772. }
  773. }
  774. // 处理正在观看的国标设备
  775. List<SsrcTransaction> allSsrc = streamSession.getAllSsrc();
  776. if (allSsrc.size() > 0) {
  777. for (SsrcTransaction ssrcTransaction : allSsrc) {
  778. if (ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  779. Device device = deviceService.getDevice(ssrcTransaction.getDeviceId());
  780. if (device == null) {
  781. continue;
  782. }
  783. try {
  784. cmder.streamByeCmd(device, ssrcTransaction.getChannelId(),
  785. ssrcTransaction.getStream(), null);
  786. } catch (InvalidArgumentException | ParseException | SipException |
  787. SsrcTransactionNotFoundException e) {
  788. logger.error("[zlm离线]为正在使用此zlm的设备, 发送BYE失败 {}", e.getMessage());
  789. }
  790. }
  791. }
  792. }
  793. }
  794. @Override
  795. public void zlmServerOnline(String mediaServerId) {
  796. // TODO 查找之前的点播,流如果不存在则给下级发送bye
  797. // MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  798. // zlmresTfulUtils.getMediaList(mediaServerItem, (mediaList ->{
  799. // Integer code = mediaList.getInteger("code");
  800. // if (code == 0) {
  801. // JSONArray data = mediaList.getJSONArray("data");
  802. // if (data == null || data.size() == 0) {
  803. // zlmServerOffline(mediaServerId);
  804. // }else {
  805. // Map<String, JSONObject> mediaListMap = new HashMap<>();
  806. // for (int i = 0; i < data.size(); i++) {
  807. // JSONObject json = data.getJSONObject(i);
  808. // String app = json.getString("app");
  809. // if ("rtp".equals(app)) {
  810. // String stream = json.getString("stream");
  811. // if (mediaListMap.get(stream) != null) {
  812. // continue;
  813. // }
  814. // mediaListMap.put(stream, json);
  815. // // 处理正在观看的国标设备
  816. // List<SsrcTransaction> ssrcTransactions = streamSession.getSsrcTransactionForAll(null, null, null, stream);
  817. // if (ssrcTransactions.size() > 0) {
  818. // for (SsrcTransaction ssrcTransaction : ssrcTransactions) {
  819. // if(ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  820. // cmder.streamByeCmd(ssrcTransaction.getDeviceId(), ssrcTransaction.getChannelId(),
  821. // ssrcTransaction.getStream(), null);
  822. // }
  823. // }
  824. // }
  825. // }
  826. // }
  827. // if (mediaListMap.size() > 0 ) {
  828. // // 处理正在向上推流的上级平台
  829. // List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  830. // if (sendRtpItems.size() > 0) {
  831. // for (SendRtpItem sendRtpItem : sendRtpItems) {
  832. // if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  833. // if (mediaListMap.get(sendRtpItem.getStreamId()) == null) {
  834. // ParentPlatform platform = storager.queryPlatformByServerGBId(sendRtpItem.getPlatformId());
  835. // sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  836. // }
  837. // }
  838. // }
  839. // }
  840. // }
  841. // }
  842. // }
  843. // }));
  844. }
  845. @Override
  846. public void pauseRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
  847. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
  848. if (null == inviteInfo || inviteInfo.getStreamInfo() == null) {
  849. logger.warn("streamId不存在!");
  850. throw new ServiceException("streamId不存在");
  851. }
  852. inviteInfo.getStreamInfo().setPause(true);
  853. inviteStreamService.updateInviteInfo(inviteInfo);
  854. MediaServerItem mediaServerItem = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
  855. if (null == mediaServerItem) {
  856. logger.warn("mediaServer 不存在!");
  857. throw new ServiceException("mediaServer不存在");
  858. }
  859. // zlm 暂停RTP超时检查
  860. JSONObject jsonObject = zlmresTfulUtils.pauseRtpCheck(mediaServerItem, streamId);
  861. if (jsonObject == null || jsonObject.getInteger("code") != 0) {
  862. throw new ServiceException("暂停RTP接收失败");
  863. }
  864. Device device = storager.queryVideoDevice(inviteInfo.getDeviceId());
  865. cmder.playPauseCmd(device, inviteInfo.getStreamInfo());
  866. }
  867. @Override
  868. public void resumeRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
  869. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
  870. if (null == inviteInfo || inviteInfo.getStreamInfo() == null) {
  871. logger.warn("streamId不存在!");
  872. throw new ServiceException("streamId不存在");
  873. }
  874. inviteInfo.getStreamInfo().setPause(false);
  875. inviteStreamService.updateInviteInfo(inviteInfo);
  876. MediaServerItem mediaServerItem = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
  877. if (null == mediaServerItem) {
  878. logger.warn("mediaServer 不存在!");
  879. throw new ServiceException("mediaServer不存在");
  880. }
  881. // zlm 暂停RTP超时检查
  882. JSONObject jsonObject = zlmresTfulUtils.resumeRtpCheck(mediaServerItem, streamId);
  883. if (jsonObject == null || jsonObject.getInteger("code") != 0) {
  884. throw new ServiceException("继续RTP接收失败");
  885. }
  886. Device device = storager.queryVideoDevice(inviteInfo.getDeviceId());
  887. cmder.playResumeCmd(device, inviteInfo.getStreamInfo());
  888. }
  889. @Override
  890. public void getSnap(String deviceId, String channelId, String fileName, ErrorCallback errorCallback) {
  891. Device device = deviceService.getDevice(deviceId);
  892. if (device == null) {
  893. errorCallback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(), InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getMsg(), null);
  894. return;
  895. }
  896. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  897. if (inviteInfo != null) {
  898. if (inviteInfo.getStreamInfo() != null) {
  899. // 已存在线直接截图
  900. MediaServerItem mediaServerItemInuse = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
  901. String streamUrl;
  902. if (mediaServerItemInuse.getRtspPort() != 0) {
  903. streamUrl = String.format("rtsp://127.0.0.1:%s/%s/%s", mediaServerItemInuse.getRtspPort(), "rtp", inviteInfo.getStreamInfo().getStream());
  904. }else {
  905. streamUrl = String.format("http://127.0.0.1:%s/%s/%s.live.mp4", mediaServerItemInuse.getHttpPort(), "rtp", inviteInfo.getStreamInfo().getStream());
  906. }
  907. String path = "snap";
  908. // 请求截图
  909. logger.info("[请求截图]: " + fileName);
  910. zlmresTfulUtils.getSnap(mediaServerItemInuse, streamUrl, 15, 1, path, fileName);
  911. File snapFile = new File(path + File.separator + fileName);
  912. if (snapFile.exists()) {
  913. errorCallback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), snapFile.getAbsoluteFile());
  914. }else {
  915. errorCallback.run(InviteErrorCode.FAIL.getCode(), InviteErrorCode.FAIL.getMsg(), null);
  916. }
  917. return;
  918. }
  919. }
  920. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  921. play(newMediaServerItem, deviceId, channelId, null, (code, msg, data)->{
  922. if (code == InviteErrorCode.SUCCESS.getCode()) {
  923. InviteInfo inviteInfoForPlay = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  924. if (inviteInfoForPlay != null && inviteInfoForPlay.getStreamInfo() != null) {
  925. getSnap(deviceId, channelId, fileName, errorCallback);
  926. }else {
  927. errorCallback.run(InviteErrorCode.FAIL.getCode(), InviteErrorCode.FAIL.getMsg(), null);
  928. }
  929. }else {
  930. errorCallback.run(InviteErrorCode.FAIL.getCode(), InviteErrorCode.FAIL.getMsg(), null);
  931. }
  932. });
  933. }
  934. }