PlayServiceImpl.java 58 KB

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