PlayServiceImpl.java 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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. }else {
  206. logger.info("[点播超时] 收流超时 deviceId: {}, channelId: {},码流类型:{},端口:{}, SSRC: {}",
  207. device.getDeviceId(), channelId, device.isSwitchPrimarySubStream() ? "辅码流" : "主码流",
  208. ssrcInfo.getPort(), ssrcInfo.getSsrc());
  209. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  210. mediaServerService.closeRTPServer(mediaServerItem.getId(), ssrcInfo.getStream());
  211. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  212. }
  213. }, userSetting.getPlayTimeout());
  214. try {
  215. cmder.playStreamCmd(mediaServerItem, ssrcInfo, device, channelId, (mediaServerItemInuse, hookParam ) -> {
  216. logger.info("收到订阅消息: " + hookParam);
  217. dynamicTask.stop(timeOutTaskKey);
  218. // hook响应
  219. StreamInfo streamInfo = onPublishHandlerForPlay(mediaServerItemInuse, hookParam, device.getDeviceId(), channelId);
  220. if (streamInfo == null){
  221. callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  222. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  223. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  224. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  225. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  226. return;
  227. }
  228. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  229. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  230. InviteErrorCode.SUCCESS.getCode(),
  231. InviteErrorCode.SUCCESS.getMsg(),
  232. streamInfo);
  233. logger.info("[点播成功] deviceId: {}, channelId:{}, 码流类型:{}", device.getDeviceId(), channelId,
  234. device.isSwitchPrimarySubStream() ? "辅码流" : "主码流");
  235. snapOnPlay(mediaServerItemInuse, device.getDeviceId(), channelId, ssrcInfo.getStream());
  236. }, (eventResult) -> {
  237. // 处理收到200ok后的TCP主动连接以及SSRC不一致的问题
  238. InviteOKHandler(eventResult, ssrcInfo, mediaServerItem, device, channelId,
  239. timeOutTaskKey, callback, inviteInfo, InviteSessionType.PLAY);
  240. }, (event) -> {
  241. logger.info("[点播失败] deviceId: {}, channelId:{}, {}: {}", device.getDeviceId(), channelId, event.statusCode, event.msg);
  242. dynamicTask.stop(timeOutTaskKey);
  243. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  244. // 释放ssrc
  245. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  246. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  247. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_ERROR.getCode(),
  248. String.format("点播失败, 错误码: %s, %s", event.statusCode, event.msg), null);
  249. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  250. InviteErrorCode.ERROR_FOR_RESET_SSRC.getCode(),
  251. String.format("点播失败, 错误码: %s, %s", event.statusCode, event.msg), null);
  252. inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getDeviceId(), channelId);
  253. });
  254. } catch (InvalidArgumentException | SipException | ParseException e) {
  255. logger.error("[命令发送失败] 点播消息: {}", e.getMessage());
  256. dynamicTask.stop(timeOutTaskKey);
  257. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  258. // 释放ssrc
  259. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  260. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  261. callback.run(InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getCode(),
  262. InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getMsg(), null);
  263. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  264. InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getCode(),
  265. InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getMsg(), null);
  266. inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getDeviceId(), channelId);
  267. }
  268. }
  269. private void tcpActiveHandler(Device device, String channelId, String contentString,
  270. MediaServerItem mediaServerItem,
  271. String timeOutTaskKey, SSRCInfo ssrcInfo, ErrorCallback<Object> callback){
  272. if (!device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE")) {
  273. return;
  274. }
  275. String substring;
  276. if (contentString.indexOf("y=") > 0) {
  277. substring = contentString.substring(0, contentString.indexOf("y="));
  278. }else {
  279. substring = contentString;
  280. }
  281. try {
  282. SessionDescription sdp = SdpFactory.getInstance().createSessionDescription(substring);
  283. int port = -1;
  284. Vector mediaDescriptions = sdp.getMediaDescriptions(true);
  285. for (Object description : mediaDescriptions) {
  286. MediaDescription mediaDescription = (MediaDescription) description;
  287. Media media = mediaDescription.getMedia();
  288. Vector mediaFormats = media.getMediaFormats(false);
  289. if (mediaFormats.contains("96")) {
  290. port = media.getMediaPort();
  291. break;
  292. }
  293. }
  294. logger.info("[TCP主动连接对方] deviceId: {}, channelId: {}, 连接对方的地址:{}:{}, 收流模式:{}, SSRC: {}, SSRC校验:{}", device.getDeviceId(), channelId, sdp.getConnection().getAddress(), port, device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
  295. JSONObject jsonObject = zlmresTfulUtils.connectRtpServer(mediaServerItem, sdp.getConnection().getAddress(), port, ssrcInfo.getStream());
  296. logger.info("[TCP主动连接对方] 结果: {}", jsonObject);
  297. } catch (SdpException e) {
  298. logger.error("[TCP主动连接对方] deviceId: {}, channelId: {}, 解析200OK的SDP信息失败", device.getDeviceId(), channelId, e);
  299. dynamicTask.stop(timeOutTaskKey);
  300. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  301. // 释放ssrc
  302. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  303. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  304. callback.run(InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getCode(),
  305. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getMsg(), null);
  306. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  307. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getCode(),
  308. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getMsg(), null);
  309. }
  310. }
  311. /**
  312. * 点播成功时调用截图.
  313. *
  314. * @param mediaServerItemInuse media
  315. * @param deviceId 设备 ID
  316. * @param channelId 通道 ID
  317. * @param stream ssrc
  318. */
  319. private void snapOnPlay(MediaServerItem mediaServerItemInuse, String deviceId, String channelId, String stream) {
  320. String streamUrl;
  321. if (mediaServerItemInuse.getRtspPort() != 0) {
  322. streamUrl = String.format("rtsp://127.0.0.1:%s/%s/%s", mediaServerItemInuse.getRtspPort(), "rtp", stream);
  323. } else {
  324. streamUrl = String.format("http://127.0.0.1:%s/%s/%s.live.mp4", mediaServerItemInuse.getHttpPort(), "rtp", stream);
  325. }
  326. String path = "snap";
  327. String fileName = deviceId + "_" + channelId + ".jpg";
  328. // 请求截图
  329. logger.info("[请求截图]: " + fileName);
  330. zlmresTfulUtils.getSnap(mediaServerItemInuse, streamUrl, 15, 1, path, fileName);
  331. }
  332. private StreamInfo onPublishHandlerForPlay(MediaServerItem mediaServerItem, HookParam hookParam, String deviceId, String channelId) {
  333. StreamInfo streamInfo = null;
  334. Device device = redisCatchStorage.getDevice(deviceId);
  335. OnStreamChangedHookParam streamChangedHookParam = (OnStreamChangedHookParam)hookParam;
  336. streamInfo = onPublishHandler(mediaServerItem, streamChangedHookParam, deviceId, channelId);
  337. if (streamInfo != null) {
  338. DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
  339. if (deviceChannel != null) {
  340. deviceChannel.setStreamId(streamInfo.getStream());
  341. storager.startPlay(deviceId, channelId, streamInfo.getStream());
  342. }
  343. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  344. if (inviteInfo != null) {
  345. inviteInfo.setStatus(InviteSessionStatus.ok);
  346. inviteInfo.setStreamInfo(streamInfo);
  347. inviteStreamService.updateInviteInfo(inviteInfo);
  348. }
  349. }
  350. return streamInfo;
  351. }
  352. private StreamInfo onPublishHandlerForPlayback(MediaServerItem mediaServerItem, HookParam param, String deviceId, String channelId, String startTime, String endTime) {
  353. OnStreamChangedHookParam streamChangedHookParam = (OnStreamChangedHookParam) param;
  354. StreamInfo streamInfo = onPublishHandler(mediaServerItem, streamChangedHookParam, deviceId, channelId);
  355. if (streamInfo != null) {
  356. streamInfo.setStartTime(startTime);
  357. streamInfo.setEndTime(endTime);
  358. DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
  359. if (deviceChannel != null) {
  360. deviceChannel.setStreamId(streamInfo.getStream());
  361. storager.startPlay(deviceId, channelId, streamInfo.getStream());
  362. }
  363. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, ((OnStreamChangedHookParam) param).getStream());
  364. if (inviteInfo != null) {
  365. inviteInfo.setStatus(InviteSessionStatus.ok);
  366. inviteInfo.setStreamInfo(streamInfo);
  367. inviteStreamService.updateInviteInfo(inviteInfo);
  368. }
  369. }
  370. return streamInfo;
  371. }
  372. @Override
  373. public MediaServerItem getNewMediaServerItem(Device device) {
  374. if (device == null) {
  375. return null;
  376. }
  377. MediaServerItem mediaServerItem;
  378. if (ObjectUtils.isEmpty(device.getMediaServerId()) || "auto".equals(device.getMediaServerId())) {
  379. mediaServerItem = mediaServerService.getMediaServerForMinimumLoad(null);
  380. } else {
  381. mediaServerItem = mediaServerService.getOne(device.getMediaServerId());
  382. }
  383. if (mediaServerItem == null) {
  384. logger.warn("点播时未找到可使用的ZLM...");
  385. }
  386. return mediaServerItem;
  387. }
  388. @Override
  389. public MediaServerItem getNewMediaServerItemHasAssist(Device device) {
  390. if (device == null) {
  391. return null;
  392. }
  393. MediaServerItem mediaServerItem;
  394. if (ObjectUtils.isEmpty(device.getMediaServerId()) || "auto".equals(device.getMediaServerId())) {
  395. mediaServerItem = mediaServerService.getMediaServerForMinimumLoad(true);
  396. } else {
  397. mediaServerItem = mediaServerService.getOne(device.getMediaServerId());
  398. }
  399. if (mediaServerItem == null) {
  400. logger.warn("[获取可用的ZLM节点]未找到可使用的ZLM...");
  401. }
  402. return mediaServerItem;
  403. }
  404. @Override
  405. public void playBack(String deviceId, String channelId, String startTime,
  406. String endTime, ErrorCallback<Object> callback) {
  407. Device device = storager.queryVideoDevice(deviceId);
  408. if (device == null) {
  409. logger.warn("[录像回放] 未找到设备 deviceId: {},channelId:{}", deviceId, channelId);
  410. throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到设备:" + deviceId);
  411. }
  412. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  413. if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE") && ! newMediaServerItem.isRtpEnable()) {
  414. logger.warn("[录像回放] 单端口收流时不支持TCP主动方式收流 deviceId: {},channelId:{}", deviceId, channelId);
  415. throw new ControllerException(ErrorCode.ERROR100.getCode(), "单端口收流时不支持TCP主动方式收流");
  416. }
  417. String startTimeStr = startTime.replace("-", "")
  418. .replace(":", "")
  419. .replace(" ", "");
  420. String endTimeTimeStr = endTime.replace("-", "")
  421. .replace(":", "")
  422. .replace(" ", "");
  423. String stream = deviceId + "_" + channelId + "_" + startTimeStr + "_" + endTimeTimeStr;
  424. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, stream, null, device.isSsrcCheck(), true, 0, false, device.getStreamModeForParam());
  425. playBack(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, callback);
  426. }
  427. @Override
  428. public void playBack(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo,
  429. String deviceId, String channelId, String startTime,
  430. String endTime, ErrorCallback<Object> callback) {
  431. if (mediaServerItem == null || ssrcInfo == null) {
  432. callback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(),
  433. InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getMsg(),
  434. null);
  435. return;
  436. }
  437. Device device = storager.queryVideoDevice(deviceId);
  438. if (device == null) {
  439. throw new ControllerException(ErrorCode.ERROR100.getCode(), "设备: " + deviceId + "不存在");
  440. }
  441. logger.info("[录像回放] deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}, 收流端口:{}, 收流模式:{}, SSRC: {}, SSRC校验:{}",
  442. device.getDeviceId(), channelId, startTime, endTime, ssrcInfo.getPort(), device.getStreamMode(),
  443. ssrcInfo.getSsrc(), device.isSsrcCheck());
  444. // 初始化redis中的invite消息状态
  445. InviteInfo inviteInfo = InviteInfo.getInviteInfo(device.getDeviceId(), channelId, ssrcInfo.getStream(), ssrcInfo,
  446. mediaServerItem.getSdpIp(), ssrcInfo.getPort(), device.getStreamMode(), InviteSessionType.PLAYBACK,
  447. InviteSessionStatus.ready);
  448. inviteStreamService.updateInviteInfo(inviteInfo);
  449. String playBackTimeOutTaskKey = UUID.randomUUID().toString();
  450. dynamicTask.startDelay(playBackTimeOutTaskKey, () -> {
  451. logger.warn("[录像回放] 超时,deviceId:{} ,channelId:{}", deviceId, channelId);
  452. inviteStreamService.removeInviteInfo(inviteInfo);
  453. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getMsg(), null);
  454. try {
  455. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
  456. } catch (InvalidArgumentException | ParseException | SipException e) {
  457. logger.error("[录像回放] 超时 发送BYE失败 {}", e.getMessage());
  458. } catch (SsrcTransactionNotFoundException e) {
  459. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  460. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  461. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  462. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  463. }
  464. }, userSetting.getPlayTimeout());
  465. SipSubscribe.Event errorEvent = event -> {
  466. logger.info("[录像回放] 失败,{} {}", event.statusCode, event.msg);
  467. dynamicTask.stop(playBackTimeOutTaskKey);
  468. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_ERROR.getCode(),
  469. String.format("回放失败, 错误码: %s, %s", event.statusCode, event.msg), null);
  470. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  471. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  472. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  473. inviteStreamService.removeInviteInfo(inviteInfo);
  474. };
  475. ZlmHttpHookSubscribe.Event hookEvent = (mediaServerItemInuse, hookParam) -> {
  476. logger.info("收到回放订阅消息: " + hookParam);
  477. dynamicTask.stop(playBackTimeOutTaskKey);
  478. StreamInfo streamInfo = onPublishHandlerForPlayback(mediaServerItemInuse, hookParam, deviceId, channelId, startTime, endTime);
  479. if (streamInfo == null) {
  480. logger.warn("设备回放API调用失败!");
  481. callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  482. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  483. return;
  484. }
  485. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  486. logger.info("[录像回放] 成功 deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}", device.getDeviceId(), channelId, startTime, endTime);
  487. };
  488. try {
  489. cmder.playbackStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime,
  490. hookEvent, eventResult -> {
  491. // 处理收到200ok后的TCP主动连接以及SSRC不一致的问题
  492. InviteOKHandler(eventResult, ssrcInfo, mediaServerItem, device, channelId,
  493. playBackTimeOutTaskKey, callback, inviteInfo, InviteSessionType.PLAYBACK);
  494. }, errorEvent);
  495. } catch (InvalidArgumentException | SipException | ParseException e) {
  496. logger.error("[命令发送失败] 录像回放: {}", e.getMessage());
  497. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult();
  498. eventResult.type = SipSubscribe.EventResultType.cmdSendFailEvent;
  499. eventResult.statusCode = -1;
  500. eventResult.msg = "命令发送失败";
  501. errorEvent.response(eventResult);
  502. }
  503. }
  504. private void InviteOKHandler(SipSubscribe.EventResult eventResult, SSRCInfo ssrcInfo, MediaServerItem mediaServerItem,
  505. Device device, String channelId, String timeOutTaskKey, ErrorCallback<Object> callback,
  506. InviteInfo inviteInfo, InviteSessionType inviteSessionType){
  507. inviteInfo.setStatus(InviteSessionStatus.ok);
  508. ResponseEvent responseEvent = (ResponseEvent) eventResult.event;
  509. String contentString = new String(responseEvent.getResponse().getRawContent());
  510. String ssrcInResponse = SipUtils.getSsrcFromSdp(contentString);
  511. // 兼容回复的消息中缺少ssrc(y字段)的情况
  512. if (ssrcInResponse == null) {
  513. ssrcInResponse = ssrcInfo.getSsrc();
  514. }
  515. if (ssrcInfo.getSsrc().equals(ssrcInResponse)) {
  516. // ssrc 一致
  517. if (mediaServerItem.isRtpEnable()) {
  518. // 多端口
  519. if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE")) {
  520. tcpActiveHandler(device, channelId, contentString, mediaServerItem, timeOutTaskKey, ssrcInfo, callback);
  521. }
  522. }else {
  523. // 单端口
  524. if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE")) {
  525. logger.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流");
  526. }
  527. }
  528. }else {
  529. logger.info("[Invite 200OK] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse);
  530. // ssrc 不一致
  531. if (mediaServerItem.isRtpEnable()) {
  532. // 多端口
  533. if (device.isSsrcCheck()) {
  534. // ssrc检验
  535. // 更新ssrc
  536. logger.info("[Invite 200OK] SSRC修正 {}->{}", ssrcInfo.getSsrc(), ssrcInResponse);
  537. // 释放ssrc
  538. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  539. Boolean result = mediaServerService.updateRtpServerSSRC(mediaServerItem, ssrcInfo.getStream(), ssrcInResponse);
  540. if (!result) {
  541. try {
  542. logger.warn("[Invite 200OK] 更新ssrc失败,停止点播 {}/{}", device.getDeviceId(), channelId);
  543. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null, null);
  544. } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) {
  545. logger.error("[命令发送失败] 停止播放, 发送BYE: {}", e.getMessage());
  546. }
  547. dynamicTask.stop(timeOutTaskKey);
  548. // 释放ssrc
  549. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  550. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  551. callback.run(InviteErrorCode.ERROR_FOR_RESET_SSRC.getCode(),
  552. "下级自定义了ssrc,重新设置收流信息失败", null);
  553. inviteStreamService.call(inviteSessionType, device.getDeviceId(), channelId, null,
  554. InviteErrorCode.ERROR_FOR_RESET_SSRC.getCode(),
  555. "下级自定义了ssrc,重新设置收流信息失败", null);
  556. }else {
  557. ssrcInfo.setSsrc(ssrcInResponse);
  558. inviteInfo.setSsrcInfo(ssrcInfo);
  559. inviteInfo.setStream(ssrcInfo.getStream());
  560. if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE")) {
  561. if (mediaServerItem.isRtpEnable()) {
  562. tcpActiveHandler(device, channelId, contentString, mediaServerItem, timeOutTaskKey, ssrcInfo, callback);
  563. }else {
  564. logger.warn("[Invite 200OK] 单端口收流模式不支持tcp主动模式收流");
  565. }
  566. }
  567. inviteStreamService.updateInviteInfo(inviteInfo);
  568. }
  569. }
  570. }else {
  571. if (ssrcInResponse != null) {
  572. // 单端口
  573. // 重新订阅流上线
  574. SsrcTransaction ssrcTransaction = streamSession.getSsrcTransaction(inviteInfo.getDeviceId(),
  575. inviteInfo.getChannelId(), null, inviteInfo.getStream());
  576. streamSession.remove(inviteInfo.getDeviceId(),
  577. inviteInfo.getChannelId(), inviteInfo.getStream());
  578. inviteStreamService.updateInviteInfoForSSRC(inviteInfo, ssrcInResponse);
  579. streamSession.put(device.getDeviceId(), channelId, ssrcTransaction.getCallId(),
  580. inviteInfo.getStream(), ssrcInResponse, mediaServerItem.getId(), (SIPResponse) responseEvent.getResponse(), inviteSessionType);
  581. }
  582. }
  583. }
  584. }
  585. @Override
  586. public void download(String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, ErrorCallback<Object> callback) {
  587. Device device = storager.queryVideoDevice(deviceId);
  588. if (device == null) {
  589. return;
  590. }
  591. MediaServerItem newMediaServerItem = getNewMediaServerItemHasAssist(device);
  592. if (newMediaServerItem == null) {
  593. callback.run(InviteErrorCode.ERROR_FOR_ASSIST_NOT_READY.getCode(),
  594. InviteErrorCode.ERROR_FOR_ASSIST_NOT_READY.getMsg(),
  595. null);
  596. return;
  597. }
  598. // 录像下载不使用固定流地址,固定流地址会导致如果开始时间与结束时间一致时文件错误的叠加在一起
  599. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, null, device.isSsrcCheck(), true, 0, false, device.getStreamModeForParam());
  600. download(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, downloadSpeed, callback);
  601. }
  602. @Override
  603. public void download(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo, String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, ErrorCallback<Object> callback) {
  604. if (mediaServerItem == null || ssrcInfo == null) {
  605. callback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(),
  606. InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getMsg(),
  607. null);
  608. return;
  609. }
  610. Device device = storager.queryVideoDevice(deviceId);
  611. if (device == null) {
  612. callback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(),
  613. "设备:" + deviceId + "不存在",
  614. null);
  615. return;
  616. }
  617. logger.info("[录像下载] deviceId: {}, channelId: {}, 下载速度:{}, 收流端口:{}, 收流模式:{}, SSRC: {}, SSRC校验:{}", device.getDeviceId(), channelId, downloadSpeed, ssrcInfo.getPort(), device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
  618. // 初始化redis中的invite消息状态
  619. InviteInfo inviteInfo = InviteInfo.getInviteInfo(device.getDeviceId(), channelId, ssrcInfo.getStream(), ssrcInfo,
  620. mediaServerItem.getSdpIp(), ssrcInfo.getPort(), device.getStreamMode(), InviteSessionType.DOWNLOAD,
  621. InviteSessionStatus.ready);
  622. inviteStreamService.updateInviteInfo(inviteInfo);
  623. String downLoadTimeOutTaskKey = UUID.randomUUID().toString();
  624. dynamicTask.startDelay(downLoadTimeOutTaskKey, () -> {
  625. logger.warn(String.format("录像下载请求超时,deviceId:%s ,channelId:%s", deviceId, channelId));
  626. inviteStreamService.removeInviteInfo(inviteInfo);
  627. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getCode(),
  628. InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getMsg(), null);
  629. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  630. try {
  631. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
  632. } catch (InvalidArgumentException | ParseException | SipException e) {
  633. logger.error("[录像流]录像下载请求超时, 发送BYE失败 {}", e.getMessage());
  634. } catch (SsrcTransactionNotFoundException e) {
  635. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  636. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  637. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  638. }
  639. }, userSetting.getPlayTimeout());
  640. SipSubscribe.Event errorEvent = event -> {
  641. dynamicTask.stop(downLoadTimeOutTaskKey);
  642. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getCode(),
  643. String.format("录像下载失败, 错误码: %s, %s", event.statusCode, event.msg), null);
  644. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  645. inviteStreamService.removeInviteInfo(inviteInfo);
  646. };
  647. ZlmHttpHookSubscribe.Event hookEvent = (mediaServerItemInuse, hookParam) -> {
  648. logger.info("[录像下载]收到订阅消息: " + hookParam);
  649. dynamicTask.stop(downLoadTimeOutTaskKey);
  650. StreamInfo streamInfo = onPublishHandlerForDownload(mediaServerItemInuse, hookParam, deviceId, channelId, startTime, endTime);
  651. if (streamInfo == null) {
  652. logger.warn("[录像下载] 获取流地址信息失败");
  653. callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  654. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  655. return;
  656. }
  657. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  658. logger.info("[录像下载] 调用成功 deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}", device.getDeviceId(), channelId, startTime, endTime);
  659. };
  660. try {
  661. cmder.downloadStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, downloadSpeed,
  662. hookEvent, errorEvent, eventResult ->{
  663. // 处理收到200ok后的TCP主动连接以及SSRC不一致的问题
  664. InviteOKHandler(eventResult, ssrcInfo, mediaServerItem, device, channelId,
  665. downLoadTimeOutTaskKey, callback, inviteInfo, InviteSessionType.DOWNLOAD);
  666. });
  667. } catch (InvalidArgumentException | SipException | ParseException e) {
  668. logger.error("[命令发送失败] 录像下载: {}", e.getMessage());
  669. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult();
  670. eventResult.type = SipSubscribe.EventResultType.cmdSendFailEvent;
  671. eventResult.statusCode = -1;
  672. eventResult.msg = "命令发送失败";
  673. errorEvent.response(eventResult);
  674. }
  675. }
  676. @Override
  677. public StreamInfo getDownLoadInfo(String deviceId, String channelId, String stream) {
  678. InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.DOWNLOAD, deviceId, channelId, stream);
  679. if (inviteInfo != null && inviteInfo.getStreamInfo() != null) {
  680. if (inviteInfo.getStreamInfo().getProgress() == 1) {
  681. return inviteInfo.getStreamInfo();
  682. }
  683. // 获取当前已下载时长
  684. String mediaServerId = inviteInfo.getStreamInfo().getMediaServerId();
  685. MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  686. if (mediaServerItem == null) {
  687. logger.warn("查询录像信息时发现节点已离线");
  688. return null;
  689. }
  690. if (mediaServerItem.getRecordAssistPort() > 0) {
  691. JSONObject jsonObject = assistRESTfulUtils.fileDuration(mediaServerItem, inviteInfo.getStreamInfo().getApp(), inviteInfo.getStreamInfo().getStream(), null);
  692. if (jsonObject == null) {
  693. throw new ControllerException(ErrorCode.ERROR100.getCode(), "连接Assist服务失败");
  694. }
  695. if (jsonObject.getInteger("code") == 0) {
  696. long duration = jsonObject.getLong("data");
  697. if (duration == 0) {
  698. inviteInfo.getStreamInfo().setProgress(0);
  699. } else {
  700. String startTime = inviteInfo.getStreamInfo().getStartTime();
  701. String endTime = inviteInfo.getStreamInfo().getEndTime();
  702. long start = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(startTime);
  703. long end = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(endTime);
  704. BigDecimal currentCount = new BigDecimal(duration / 1000);
  705. BigDecimal totalCount = new BigDecimal(end - start);
  706. BigDecimal divide = currentCount.divide(totalCount, 2, RoundingMode.HALF_UP);
  707. double process = divide.doubleValue();
  708. inviteInfo.getStreamInfo().setProgress(process);
  709. }
  710. inviteStreamService.updateInviteInfo(inviteInfo);
  711. }
  712. }
  713. return inviteInfo.getStreamInfo();
  714. }
  715. return null;
  716. }
  717. private StreamInfo onPublishHandlerForDownload(MediaServerItem mediaServerItemInuse, HookParam hookParam, String deviceId, String channelId, String startTime, String endTime) {
  718. OnStreamChangedHookParam streamChangedHookParam = (OnStreamChangedHookParam) hookParam;
  719. StreamInfo streamInfo = onPublishHandler(mediaServerItemInuse, streamChangedHookParam, deviceId, channelId);
  720. if (streamInfo != null) {
  721. streamInfo.setProgress(0);
  722. streamInfo.setStartTime(startTime);
  723. streamInfo.setEndTime(endTime);
  724. InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.DOWNLOAD, deviceId, channelId, streamInfo.getStream());
  725. if (inviteInfo != null) {
  726. logger.info("[录像下载] 更新invite消息中的stream信息");
  727. inviteInfo.setStatus(InviteSessionStatus.ok);
  728. inviteInfo.setStreamInfo(streamInfo);
  729. inviteStreamService.updateInviteInfo(inviteInfo);
  730. }
  731. }
  732. return streamInfo;
  733. }
  734. public StreamInfo onPublishHandler(MediaServerItem mediaServerItem, OnStreamChangedHookParam hookParam, String deviceId, String channelId) {
  735. StreamInfo streamInfo = mediaService.getStreamInfoByAppAndStream(mediaServerItem, "rtp", hookParam.getStream(), hookParam.getTracks(), null);
  736. streamInfo.setDeviceID(deviceId);
  737. streamInfo.setChannelId(channelId);
  738. return streamInfo;
  739. }
  740. @Override
  741. public void zlmServerOffline(String mediaServerId) {
  742. // 处理正在向上推流的上级平台
  743. List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  744. if (sendRtpItems.size() > 0) {
  745. for (SendRtpItem sendRtpItem : sendRtpItems) {
  746. if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  747. ParentPlatform platform = storager.queryParentPlatByServerGBId(sendRtpItem.getPlatformId());
  748. try {
  749. sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  750. } catch (SipException | InvalidArgumentException | ParseException e) {
  751. logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
  752. }
  753. }
  754. }
  755. }
  756. // 处理正在观看的国标设备
  757. List<SsrcTransaction> allSsrc = streamSession.getAllSsrc();
  758. if (allSsrc.size() > 0) {
  759. for (SsrcTransaction ssrcTransaction : allSsrc) {
  760. if (ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  761. Device device = deviceService.getDevice(ssrcTransaction.getDeviceId());
  762. if (device == null) {
  763. continue;
  764. }
  765. try {
  766. cmder.streamByeCmd(device, ssrcTransaction.getChannelId(),
  767. ssrcTransaction.getStream(), null);
  768. } catch (InvalidArgumentException | ParseException | SipException |
  769. SsrcTransactionNotFoundException e) {
  770. logger.error("[zlm离线]为正在使用此zlm的设备, 发送BYE失败 {}", e.getMessage());
  771. }
  772. }
  773. }
  774. }
  775. }
  776. @Override
  777. public void zlmServerOnline(String mediaServerId) {
  778. // TODO 查找之前的点播,流如果不存在则给下级发送bye
  779. // MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  780. // zlmresTfulUtils.getMediaList(mediaServerItem, (mediaList ->{
  781. // Integer code = mediaList.getInteger("code");
  782. // if (code == 0) {
  783. // JSONArray data = mediaList.getJSONArray("data");
  784. // if (data == null || data.size() == 0) {
  785. // zlmServerOffline(mediaServerId);
  786. // }else {
  787. // Map<String, JSONObject> mediaListMap = new HashMap<>();
  788. // for (int i = 0; i < data.size(); i++) {
  789. // JSONObject json = data.getJSONObject(i);
  790. // String app = json.getString("app");
  791. // if ("rtp".equals(app)) {
  792. // String stream = json.getString("stream");
  793. // if (mediaListMap.get(stream) != null) {
  794. // continue;
  795. // }
  796. // mediaListMap.put(stream, json);
  797. // // 处理正在观看的国标设备
  798. // List<SsrcTransaction> ssrcTransactions = streamSession.getSsrcTransactionForAll(null, null, null, stream);
  799. // if (ssrcTransactions.size() > 0) {
  800. // for (SsrcTransaction ssrcTransaction : ssrcTransactions) {
  801. // if(ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  802. // cmder.streamByeCmd(ssrcTransaction.getDeviceId(), ssrcTransaction.getChannelId(),
  803. // ssrcTransaction.getStream(), null);
  804. // }
  805. // }
  806. // }
  807. // }
  808. // }
  809. // if (mediaListMap.size() > 0 ) {
  810. // // 处理正在向上推流的上级平台
  811. // List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  812. // if (sendRtpItems.size() > 0) {
  813. // for (SendRtpItem sendRtpItem : sendRtpItems) {
  814. // if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  815. // if (mediaListMap.get(sendRtpItem.getStreamId()) == null) {
  816. // ParentPlatform platform = storager.queryPlatformByServerGBId(sendRtpItem.getPlatformId());
  817. // sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  818. // }
  819. // }
  820. // }
  821. // }
  822. // }
  823. // }
  824. // }
  825. // }));
  826. }
  827. @Override
  828. public void pauseRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
  829. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
  830. if (null == inviteInfo || inviteInfo.getStreamInfo() == null) {
  831. logger.warn("streamId不存在!");
  832. throw new ServiceException("streamId不存在");
  833. }
  834. inviteInfo.getStreamInfo().setPause(true);
  835. inviteStreamService.updateInviteInfo(inviteInfo);
  836. MediaServerItem mediaServerItem = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
  837. if (null == mediaServerItem) {
  838. logger.warn("mediaServer 不存在!");
  839. throw new ServiceException("mediaServer不存在");
  840. }
  841. // zlm 暂停RTP超时检查
  842. JSONObject jsonObject = zlmresTfulUtils.pauseRtpCheck(mediaServerItem, streamId);
  843. if (jsonObject == null || jsonObject.getInteger("code") != 0) {
  844. throw new ServiceException("暂停RTP接收失败");
  845. }
  846. Device device = storager.queryVideoDevice(inviteInfo.getDeviceId());
  847. cmder.playPauseCmd(device, inviteInfo.getStreamInfo());
  848. }
  849. @Override
  850. public void resumeRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
  851. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
  852. if (null == inviteInfo || inviteInfo.getStreamInfo() == null) {
  853. logger.warn("streamId不存在!");
  854. throw new ServiceException("streamId不存在");
  855. }
  856. inviteInfo.getStreamInfo().setPause(false);
  857. inviteStreamService.updateInviteInfo(inviteInfo);
  858. MediaServerItem mediaServerItem = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
  859. if (null == mediaServerItem) {
  860. logger.warn("mediaServer 不存在!");
  861. throw new ServiceException("mediaServer不存在");
  862. }
  863. // zlm 暂停RTP超时检查
  864. JSONObject jsonObject = zlmresTfulUtils.resumeRtpCheck(mediaServerItem, streamId);
  865. if (jsonObject == null || jsonObject.getInteger("code") != 0) {
  866. throw new ServiceException("继续RTP接收失败");
  867. }
  868. Device device = storager.queryVideoDevice(inviteInfo.getDeviceId());
  869. cmder.playResumeCmd(device, inviteInfo.getStreamInfo());
  870. }
  871. @Override
  872. public void getSnap(String deviceId, String channelId, String fileName, ErrorCallback errorCallback) {
  873. Device device = deviceService.getDevice(deviceId);
  874. if (device == null) {
  875. errorCallback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(), InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getMsg(), null);
  876. return;
  877. }
  878. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  879. if (inviteInfo != null) {
  880. if (inviteInfo.getStreamInfo() != null) {
  881. // 已存在线直接截图
  882. MediaServerItem mediaServerItemInuse = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
  883. String streamUrl;
  884. if (mediaServerItemInuse.getRtspPort() != 0) {
  885. streamUrl = String.format("rtsp://127.0.0.1:%s/%s/%s", mediaServerItemInuse.getRtspPort(), "rtp", inviteInfo.getStreamInfo().getStream());
  886. }else {
  887. streamUrl = String.format("http://127.0.0.1:%s/%s/%s.live.mp4", mediaServerItemInuse.getHttpPort(), "rtp", inviteInfo.getStreamInfo().getStream());
  888. }
  889. String path = "snap";
  890. // 请求截图
  891. logger.info("[请求截图]: " + fileName);
  892. zlmresTfulUtils.getSnap(mediaServerItemInuse, streamUrl, 15, 1, path, fileName);
  893. File snapFile = new File(path + File.separator + fileName);
  894. if (snapFile.exists()) {
  895. errorCallback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), snapFile.getAbsoluteFile());
  896. }else {
  897. errorCallback.run(InviteErrorCode.FAIL.getCode(), InviteErrorCode.FAIL.getMsg(), null);
  898. }
  899. return;
  900. }
  901. }
  902. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  903. play(newMediaServerItem, deviceId, channelId, null, (code, msg, data)->{
  904. if (code == InviteErrorCode.SUCCESS.getCode()) {
  905. InviteInfo inviteInfoForPlay = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  906. if (inviteInfoForPlay != null && inviteInfoForPlay.getStreamInfo() != null) {
  907. getSnap(deviceId, channelId, fileName, errorCallback);
  908. }else {
  909. errorCallback.run(InviteErrorCode.FAIL.getCode(), InviteErrorCode.FAIL.getMsg(), null);
  910. }
  911. }else {
  912. errorCallback.run(InviteErrorCode.FAIL.getCode(), InviteErrorCode.FAIL.getMsg(), null);
  913. }
  914. });
  915. }
  916. }