PlayServiceImpl.java 56 KB

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