PlayServiceImpl.java 70 KB

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