PlayServiceImpl.java 56 KB

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