PlayServiceImpl.java 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. package com.genersoft.iot.vmp.service.impl;
  2. import com.alibaba.fastjson2.JSONObject;
  3. import com.genersoft.iot.vmp.common.InviteInfo;
  4. import com.genersoft.iot.vmp.common.InviteSessionStatus;
  5. import com.genersoft.iot.vmp.common.InviteSessionType;
  6. import com.genersoft.iot.vmp.common.StreamInfo;
  7. import com.genersoft.iot.vmp.conf.DynamicTask;
  8. import com.genersoft.iot.vmp.conf.UserSetting;
  9. import com.genersoft.iot.vmp.conf.exception.ControllerException;
  10. import com.genersoft.iot.vmp.conf.exception.ServiceException;
  11. import com.genersoft.iot.vmp.conf.exception.SsrcTransactionNotFoundException;
  12. import com.genersoft.iot.vmp.gb28181.bean.*;
  13. import com.genersoft.iot.vmp.gb28181.event.SipSubscribe;
  14. import com.genersoft.iot.vmp.gb28181.session.VideoStreamSessionManager;
  15. import com.genersoft.iot.vmp.gb28181.transmit.callback.DeferredResultHolder;
  16. import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
  17. import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommanderFroPlatform;
  18. import com.genersoft.iot.vmp.gb28181.utils.SipUtils;
  19. import com.genersoft.iot.vmp.media.zlm.AssistRESTfulUtils;
  20. import com.genersoft.iot.vmp.media.zlm.ZLMRESTfulUtils;
  21. import com.genersoft.iot.vmp.media.zlm.ZLMServerFactory;
  22. import com.genersoft.iot.vmp.media.zlm.ZlmHttpHookSubscribe;
  23. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeFactory;
  24. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeForStreamChange;
  25. import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem;
  26. import com.genersoft.iot.vmp.media.zlm.dto.hook.HookParam;
  27. import com.genersoft.iot.vmp.media.zlm.dto.hook.OnStreamChangedHookParam;
  28. import com.genersoft.iot.vmp.service.*;
  29. import com.genersoft.iot.vmp.service.bean.ErrorCallback;
  30. import com.genersoft.iot.vmp.service.bean.InviteErrorCode;
  31. import com.genersoft.iot.vmp.service.bean.SSRCInfo;
  32. import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
  33. import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
  34. import com.genersoft.iot.vmp.utils.DateUtil;
  35. import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
  36. import gov.nist.javax.sip.message.SIPResponse;
  37. import org.slf4j.Logger;
  38. import org.slf4j.LoggerFactory;
  39. import org.springframework.beans.factory.annotation.Autowired;
  40. import org.springframework.stereotype.Service;
  41. import org.springframework.util.ObjectUtils;
  42. import javax.sdp.*;
  43. import javax.sip.InvalidArgumentException;
  44. import javax.sip.ResponseEvent;
  45. import javax.sip.SipException;
  46. import java.io.File;
  47. import java.math.BigDecimal;
  48. import java.math.RoundingMode;
  49. import java.text.ParseException;
  50. import java.util.List;
  51. import java.util.UUID;
  52. import java.util.Vector;
  53. @SuppressWarnings(value = {"rawtypes", "unchecked"})
  54. @Service
  55. public class PlayServiceImpl implements IPlayService {
  56. private final static Logger logger = LoggerFactory.getLogger(PlayServiceImpl.class);
  57. @Autowired
  58. private IVideoManagerStorage storager;
  59. @Autowired
  60. private SIPCommander cmder;
  61. @Autowired
  62. private SIPCommanderFroPlatform sipCommanderFroPlatform;
  63. @Autowired
  64. private IRedisCatchStorage redisCatchStorage;
  65. @Autowired
  66. private IInviteStreamService inviteStreamService;
  67. @Autowired
  68. private DeferredResultHolder resultHolder;
  69. @Autowired
  70. private ZLMRESTfulUtils zlmresTfulUtils;
  71. @Autowired
  72. private ZLMServerFactory zlmServerFactory;
  73. @Autowired
  74. private AssistRESTfulUtils assistRESTfulUtils;
  75. @Autowired
  76. private IMediaService mediaService;
  77. @Autowired
  78. private IMediaServerService mediaServerService;
  79. @Autowired
  80. private VideoStreamSessionManager streamSession;
  81. @Autowired
  82. private IDeviceService deviceService;
  83. @Autowired
  84. private UserSetting userSetting;
  85. @Autowired
  86. private DynamicTask dynamicTask;
  87. @Autowired
  88. private ZlmHttpHookSubscribe subscribe;
  89. @Override
  90. public SSRCInfo play(MediaServerItem mediaServerItem, String deviceId, String channelId, String ssrc, ErrorCallback<Object> callback) {
  91. if (mediaServerItem == null) {
  92. logger.warn("[点播] 未找到可用的zlm deviceId: {},channelId:{}", deviceId, channelId);
  93. throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到可用的zlm");
  94. }
  95. Device device = redisCatchStorage.getDevice(deviceId);
  96. if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE") && !mediaServerItem.isRtpEnable()) {
  97. logger.warn("[点播] 单端口收流时不支持TCP主动方式收流 deviceId: {},channelId:{}", deviceId, channelId);
  98. throw new ControllerException(ErrorCode.ERROR100.getCode(), "单端口收流时不支持TCP主动方式收流");
  99. }
  100. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  101. if (inviteInfo != null ) {
  102. if (inviteInfo.getStreamInfo() == null) {
  103. // 点播发起了但是尚未成功, 仅注册回调等待结果即可
  104. inviteStreamService.once(InviteSessionType.PLAY, deviceId, channelId, null, callback);
  105. logger.info("[点播开始] 已经请求中,等待结果, deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
  106. return inviteInfo.getSsrcInfo();
  107. }else {
  108. StreamInfo streamInfo = inviteInfo.getStreamInfo();
  109. String streamId = streamInfo.getStream();
  110. if (streamId == null) {
  111. callback.run(InviteErrorCode.ERROR_FOR_CATCH_DATA.getCode(), "点播失败, redis缓存streamId等于null", null);
  112. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  113. InviteErrorCode.ERROR_FOR_CATCH_DATA.getCode(),
  114. "点播失败, redis缓存streamId等于null",
  115. null);
  116. return inviteInfo.getSsrcInfo();
  117. }
  118. String mediaServerId = streamInfo.getMediaServerId();
  119. MediaServerItem mediaInfo = mediaServerService.getOne(mediaServerId);
  120. Boolean ready = zlmServerFactory.isStreamReady(mediaInfo, "rtp", streamId);
  121. if (ready != null && ready) {
  122. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  123. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  124. InviteErrorCode.SUCCESS.getCode(),
  125. InviteErrorCode.SUCCESS.getMsg(),
  126. streamInfo);
  127. logger.info("[点播已存在] 直接返回, deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
  128. return inviteInfo.getSsrcInfo();
  129. }else {
  130. // 点播发起了但是尚未成功, 仅注册回调等待结果即可
  131. inviteStreamService.once(InviteSessionType.PLAY, deviceId, channelId, null, callback);
  132. storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId());
  133. inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  134. }
  135. }
  136. }
  137. String streamId = 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.getInviteInfoByStream(InviteSessionType.PLAYBACK, ((OnStreamChangedHookParam) param).getStream());
  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. } catch (InvalidArgumentException | SipException | ParseException e) {
  651. logger.error("[命令发送失败] 录像下载: {}", e.getMessage());
  652. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult();
  653. eventResult.type = SipSubscribe.EventResultType.cmdSendFailEvent;
  654. eventResult.statusCode = -1;
  655. eventResult.msg = "命令发送失败";
  656. errorEvent.response(eventResult);
  657. }
  658. }
  659. @Override
  660. public StreamInfo getDownLoadInfo(String deviceId, String channelId, String stream) {
  661. InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.DOWNLOAD, deviceId, channelId, stream);
  662. if (inviteInfo != null && inviteInfo.getStreamInfo() != null) {
  663. if (inviteInfo.getStreamInfo().getProgress() == 1) {
  664. return inviteInfo.getStreamInfo();
  665. }
  666. // 获取当前已下载时长
  667. String mediaServerId = inviteInfo.getStreamInfo().getMediaServerId();
  668. MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  669. if (mediaServerItem == null) {
  670. logger.warn("查询录像信息时发现节点已离线");
  671. return null;
  672. }
  673. if (mediaServerItem.getRecordAssistPort() > 0) {
  674. JSONObject jsonObject = assistRESTfulUtils.fileDuration(mediaServerItem, inviteInfo.getStreamInfo().getApp(), inviteInfo.getStreamInfo().getStream(), null);
  675. if (jsonObject == null) {
  676. throw new ControllerException(ErrorCode.ERROR100.getCode(), "连接Assist服务失败");
  677. }
  678. if (jsonObject.getInteger("code") == 0) {
  679. long duration = jsonObject.getLong("data");
  680. if (duration == 0) {
  681. inviteInfo.getStreamInfo().setProgress(0);
  682. } else {
  683. String startTime = inviteInfo.getStreamInfo().getStartTime();
  684. String endTime = inviteInfo.getStreamInfo().getEndTime();
  685. long start = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(startTime);
  686. long end = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(endTime);
  687. BigDecimal currentCount = new BigDecimal(duration / 1000);
  688. BigDecimal totalCount = new BigDecimal(end - start);
  689. BigDecimal divide = currentCount.divide(totalCount, 2, RoundingMode.HALF_UP);
  690. double process = divide.doubleValue();
  691. inviteInfo.getStreamInfo().setProgress(process);
  692. }
  693. inviteStreamService.updateInviteInfo(inviteInfo);
  694. }
  695. }
  696. return inviteInfo.getStreamInfo();
  697. }
  698. return null;
  699. }
  700. private StreamInfo onPublishHandlerForDownload(MediaServerItem mediaServerItemInuse, HookParam hookParam, String deviceId, String channelId, String startTime, String endTime) {
  701. OnStreamChangedHookParam streamChangedHookParam = (OnStreamChangedHookParam) hookParam;
  702. StreamInfo streamInfo = onPublishHandler(mediaServerItemInuse, streamChangedHookParam, deviceId, channelId);
  703. if (streamInfo != null) {
  704. streamInfo.setProgress(0);
  705. streamInfo.setStartTime(startTime);
  706. streamInfo.setEndTime(endTime);
  707. InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.DOWNLOAD, deviceId, channelId, streamInfo.getStream());
  708. if (inviteInfo != null) {
  709. logger.info("[录像下载] 更新invite消息中的stream信息");
  710. inviteInfo.setStatus(InviteSessionStatus.ok);
  711. inviteInfo.setStreamInfo(streamInfo);
  712. inviteStreamService.updateInviteInfo(inviteInfo);
  713. }
  714. }
  715. return streamInfo;
  716. }
  717. public StreamInfo onPublishHandler(MediaServerItem mediaServerItem, OnStreamChangedHookParam hookParam, String deviceId, String channelId) {
  718. StreamInfo streamInfo = mediaService.getStreamInfoByAppAndStream(mediaServerItem, "rtp", hookParam.getStream(), hookParam.getTracks(), null);
  719. streamInfo.setDeviceID(deviceId);
  720. streamInfo.setChannelId(channelId);
  721. return streamInfo;
  722. }
  723. @Override
  724. public void zlmServerOffline(String mediaServerId) {
  725. // 处理正在向上推流的上级平台
  726. List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  727. if (sendRtpItems.size() > 0) {
  728. for (SendRtpItem sendRtpItem : sendRtpItems) {
  729. if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  730. ParentPlatform platform = storager.queryParentPlatByServerGBId(sendRtpItem.getPlatformId());
  731. try {
  732. sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  733. } catch (SipException | InvalidArgumentException | ParseException e) {
  734. logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
  735. }
  736. }
  737. }
  738. }
  739. // 处理正在观看的国标设备
  740. List<SsrcTransaction> allSsrc = streamSession.getAllSsrc();
  741. if (allSsrc.size() > 0) {
  742. for (SsrcTransaction ssrcTransaction : allSsrc) {
  743. if (ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  744. Device device = deviceService.getDevice(ssrcTransaction.getDeviceId());
  745. if (device == null) {
  746. continue;
  747. }
  748. try {
  749. cmder.streamByeCmd(device, ssrcTransaction.getChannelId(),
  750. ssrcTransaction.getStream(), null);
  751. } catch (InvalidArgumentException | ParseException | SipException |
  752. SsrcTransactionNotFoundException e) {
  753. logger.error("[zlm离线]为正在使用此zlm的设备, 发送BYE失败 {}", e.getMessage());
  754. }
  755. }
  756. }
  757. }
  758. }
  759. @Override
  760. public void zlmServerOnline(String mediaServerId) {
  761. // TODO 查找之前的点播,流如果不存在则给下级发送bye
  762. // MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  763. // zlmresTfulUtils.getMediaList(mediaServerItem, (mediaList ->{
  764. // Integer code = mediaList.getInteger("code");
  765. // if (code == 0) {
  766. // JSONArray data = mediaList.getJSONArray("data");
  767. // if (data == null || data.size() == 0) {
  768. // zlmServerOffline(mediaServerId);
  769. // }else {
  770. // Map<String, JSONObject> mediaListMap = new HashMap<>();
  771. // for (int i = 0; i < data.size(); i++) {
  772. // JSONObject json = data.getJSONObject(i);
  773. // String app = json.getString("app");
  774. // if ("rtp".equals(app)) {
  775. // String stream = json.getString("stream");
  776. // if (mediaListMap.get(stream) != null) {
  777. // continue;
  778. // }
  779. // mediaListMap.put(stream, json);
  780. // // 处理正在观看的国标设备
  781. // List<SsrcTransaction> ssrcTransactions = streamSession.getSsrcTransactionForAll(null, null, null, stream);
  782. // if (ssrcTransactions.size() > 0) {
  783. // for (SsrcTransaction ssrcTransaction : ssrcTransactions) {
  784. // if(ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  785. // cmder.streamByeCmd(ssrcTransaction.getDeviceId(), ssrcTransaction.getChannelId(),
  786. // ssrcTransaction.getStream(), null);
  787. // }
  788. // }
  789. // }
  790. // }
  791. // }
  792. // if (mediaListMap.size() > 0 ) {
  793. // // 处理正在向上推流的上级平台
  794. // List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  795. // if (sendRtpItems.size() > 0) {
  796. // for (SendRtpItem sendRtpItem : sendRtpItems) {
  797. // if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  798. // if (mediaListMap.get(sendRtpItem.getStreamId()) == null) {
  799. // ParentPlatform platform = storager.queryPlatformByServerGBId(sendRtpItem.getPlatformId());
  800. // sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  801. // }
  802. // }
  803. // }
  804. // }
  805. // }
  806. // }
  807. // }
  808. // }));
  809. }
  810. @Override
  811. public void pauseRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
  812. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
  813. if (null == inviteInfo || inviteInfo.getStreamInfo() == null) {
  814. logger.warn("streamId不存在!");
  815. throw new ServiceException("streamId不存在");
  816. }
  817. inviteInfo.getStreamInfo().setPause(true);
  818. inviteStreamService.updateInviteInfo(inviteInfo);
  819. MediaServerItem mediaServerItem = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
  820. if (null == mediaServerItem) {
  821. logger.warn("mediaServer 不存在!");
  822. throw new ServiceException("mediaServer不存在");
  823. }
  824. // zlm 暂停RTP超时检查
  825. JSONObject jsonObject = zlmresTfulUtils.pauseRtpCheck(mediaServerItem, streamId);
  826. if (jsonObject == null || jsonObject.getInteger("code") != 0) {
  827. throw new ServiceException("暂停RTP接收失败");
  828. }
  829. Device device = storager.queryVideoDevice(inviteInfo.getDeviceId());
  830. cmder.playPauseCmd(device, inviteInfo.getStreamInfo());
  831. }
  832. @Override
  833. public void resumeRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
  834. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
  835. if (null == inviteInfo || inviteInfo.getStreamInfo() == null) {
  836. logger.warn("streamId不存在!");
  837. throw new ServiceException("streamId不存在");
  838. }
  839. inviteInfo.getStreamInfo().setPause(false);
  840. inviteStreamService.updateInviteInfo(inviteInfo);
  841. MediaServerItem mediaServerItem = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
  842. if (null == mediaServerItem) {
  843. logger.warn("mediaServer 不存在!");
  844. throw new ServiceException("mediaServer不存在");
  845. }
  846. // zlm 暂停RTP超时检查
  847. JSONObject jsonObject = zlmresTfulUtils.resumeRtpCheck(mediaServerItem, streamId);
  848. if (jsonObject == null || jsonObject.getInteger("code") != 0) {
  849. throw new ServiceException("继续RTP接收失败");
  850. }
  851. Device device = storager.queryVideoDevice(inviteInfo.getDeviceId());
  852. cmder.playResumeCmd(device, inviteInfo.getStreamInfo());
  853. }
  854. @Override
  855. public void getSnap(String deviceId, String channelId, String fileName, ErrorCallback errorCallback) {
  856. Device device = deviceService.getDevice(deviceId);
  857. if (device == null) {
  858. errorCallback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(), InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getMsg(), null);
  859. return;
  860. }
  861. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  862. if (inviteInfo != null) {
  863. if (inviteInfo.getStreamInfo() != null) {
  864. // 已存在线直接截图
  865. MediaServerItem mediaServerItemInuse = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
  866. String streamUrl;
  867. if (mediaServerItemInuse.getRtspPort() != 0) {
  868. streamUrl = String.format("rtsp://127.0.0.1:%s/%s/%s", mediaServerItemInuse.getRtspPort(), "rtp", inviteInfo.getStreamInfo().getStream());
  869. }else {
  870. streamUrl = String.format("http://127.0.0.1:%s/%s/%s.live.mp4", mediaServerItemInuse.getHttpPort(), "rtp", inviteInfo.getStreamInfo().getStream());
  871. }
  872. String path = "snap";
  873. // 请求截图
  874. logger.info("[请求截图]: " + fileName);
  875. zlmresTfulUtils.getSnap(mediaServerItemInuse, streamUrl, 15, 1, path, fileName);
  876. File snapFile = new File(path + File.separator + fileName);
  877. if (snapFile.exists()) {
  878. errorCallback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), snapFile.getAbsoluteFile());
  879. }else {
  880. errorCallback.run(InviteErrorCode.FAIL.getCode(), InviteErrorCode.FAIL.getMsg(), null);
  881. }
  882. return;
  883. }
  884. }
  885. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  886. play(newMediaServerItem, deviceId, channelId, null, (code, msg, data)->{
  887. if (code == InviteErrorCode.SUCCESS.getCode()) {
  888. InviteInfo inviteInfoForPlay = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  889. if (inviteInfoForPlay != null && inviteInfoForPlay.getStreamInfo() != null) {
  890. getSnap(deviceId, channelId, fileName, errorCallback);
  891. }else {
  892. errorCallback.run(InviteErrorCode.FAIL.getCode(), InviteErrorCode.FAIL.getMsg(), null);
  893. }
  894. }else {
  895. errorCallback.run(InviteErrorCode.FAIL.getCode(), InviteErrorCode.FAIL.getMsg(), null);
  896. }
  897. });
  898. }
  899. }