PlayServiceImpl.java 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. package com.genersoft.iot.vmp.service.impl;
  2. import java.math.BigDecimal;
  3. import java.math.RoundingMode;
  4. import java.text.ParseException;
  5. import java.util.*;
  6. import javax.sip.InvalidArgumentException;
  7. import javax.sip.ResponseEvent;
  8. import javax.sip.SipException;
  9. import com.genersoft.iot.vmp.common.VideoManagerConstants;
  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.service.IDeviceService;
  15. import com.genersoft.iot.vmp.utils.redis.RedisUtil;
  16. import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.beans.factory.annotation.Qualifier;
  21. import org.springframework.beans.factory.annotation.Value;
  22. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  23. import org.springframework.stereotype.Service;
  24. import org.springframework.web.context.request.async.DeferredResult;
  25. import com.alibaba.fastjson.JSON;
  26. import com.alibaba.fastjson.JSONArray;
  27. import com.alibaba.fastjson.JSONObject;
  28. import com.genersoft.iot.vmp.common.StreamInfo;
  29. import com.genersoft.iot.vmp.conf.DynamicTask;
  30. import com.genersoft.iot.vmp.conf.UserSetting;
  31. import com.genersoft.iot.vmp.gb28181.event.SipSubscribe;
  32. import com.genersoft.iot.vmp.gb28181.session.VideoStreamSessionManager;
  33. import com.genersoft.iot.vmp.gb28181.transmit.callback.DeferredResultHolder;
  34. import com.genersoft.iot.vmp.gb28181.transmit.callback.RequestMessage;
  35. import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
  36. import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommanderFroPlatform;
  37. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeFactory;
  38. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeForStreamChange;
  39. import com.genersoft.iot.vmp.utils.DateUtil;
  40. import com.genersoft.iot.vmp.media.zlm.AssistRESTfulUtils;
  41. import com.genersoft.iot.vmp.media.zlm.ZlmHttpHookSubscribe;
  42. import com.genersoft.iot.vmp.media.zlm.ZLMRESTfulUtils;
  43. import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem;
  44. import com.genersoft.iot.vmp.service.IMediaServerService;
  45. import com.genersoft.iot.vmp.service.IMediaService;
  46. import com.genersoft.iot.vmp.service.IPlayService;
  47. import com.genersoft.iot.vmp.service.bean.InviteTimeOutCallback;
  48. import com.genersoft.iot.vmp.service.bean.PlayBackCallback;
  49. import com.genersoft.iot.vmp.service.bean.PlayBackResult;
  50. import com.genersoft.iot.vmp.service.bean.SSRCInfo;
  51. import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
  52. import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
  53. import com.genersoft.iot.vmp.vmanager.bean.WVPResult;
  54. import com.genersoft.iot.vmp.vmanager.gb28181.play.bean.PlayResult;
  55. import gov.nist.javax.sip.stack.SIPDialog;
  56. @SuppressWarnings(value = {"rawtypes", "unchecked"})
  57. @Service
  58. public class PlayServiceImpl implements IPlayService {
  59. private final static Logger logger = LoggerFactory.getLogger(PlayServiceImpl.class);
  60. @Autowired
  61. private IVideoManagerStorage storager;
  62. @Autowired
  63. private SIPCommander cmder;
  64. @Autowired
  65. private SIPCommanderFroPlatform sipCommanderFroPlatform;
  66. @Autowired
  67. private IRedisCatchStorage redisCatchStorage;
  68. @Autowired
  69. private DeferredResultHolder resultHolder;
  70. @Autowired
  71. private ZLMRESTfulUtils zlmresTfulUtils;
  72. @Autowired
  73. private AssistRESTfulUtils assistRESTfulUtils;
  74. @Autowired
  75. private IMediaService mediaService;
  76. @Autowired
  77. private IMediaServerService mediaServerService;
  78. @Autowired
  79. private VideoStreamSessionManager streamSession;
  80. @Autowired
  81. private IDeviceService deviceService;
  82. @Autowired
  83. private UserSetting userSetting;
  84. @Autowired
  85. private DynamicTask dynamicTask;
  86. @Autowired
  87. private ZlmHttpHookSubscribe subscribe;
  88. @Qualifier("taskExecutor")
  89. @Autowired
  90. private ThreadPoolTaskExecutor taskExecutor;
  91. @Override
  92. public PlayResult play(MediaServerItem mediaServerItem, String deviceId, String channelId,
  93. ZlmHttpHookSubscribe.Event hookEvent, SipSubscribe.Event errorEvent,
  94. Runnable timeoutCallback) {
  95. if (mediaServerItem == null) {
  96. throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到可用的zlm");
  97. }
  98. PlayResult playResult = new PlayResult();
  99. RequestMessage msg = new RequestMessage();
  100. String key = DeferredResultHolder.CALLBACK_CMD_PLAY + deviceId + channelId;
  101. msg.setKey(key);
  102. String uuid = UUID.randomUUID().toString();
  103. msg.setId(uuid);
  104. playResult.setUuid(uuid);
  105. DeferredResult<WVPResult<String>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
  106. playResult.setResult(result);
  107. // 录像查询以channelId作为deviceId查询
  108. resultHolder.put(key, uuid, result);
  109. Device device = redisCatchStorage.getDevice(deviceId);
  110. StreamInfo streamInfo = redisCatchStorage.queryPlayByDevice(deviceId, channelId);
  111. playResult.setDevice(device);
  112. result.onCompletion(() -> {
  113. // 点播结束时调用截图接口
  114. taskExecutor.execute(() -> {
  115. // TODO 应该在上流时调用更好,结束也可能是错误结束
  116. String path = "snap";
  117. String fileName = deviceId + "_" + channelId + ".jpg";
  118. WVPResult wvpResult = (WVPResult) result.getResult();
  119. if (Objects.requireNonNull(wvpResult).getCode() == 0) {
  120. StreamInfo streamInfoForSuccess = (StreamInfo) wvpResult.getData();
  121. MediaServerItem mediaInfo = mediaServerService.getOne(streamInfoForSuccess.getMediaServerId());
  122. String streamUrl = streamInfoForSuccess.getFmp4();
  123. // 请求截图
  124. logger.info("[请求截图]: " + fileName);
  125. zlmresTfulUtils.getSnap(mediaInfo, streamUrl, 15, 1, path, fileName);
  126. }
  127. });
  128. });
  129. if (streamInfo != null) {
  130. String streamId = streamInfo.getStream();
  131. if (streamId == null) {
  132. WVPResult wvpResult = new WVPResult();
  133. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  134. wvpResult.setMsg("点播失败, redis缓存streamId等于null");
  135. msg.setData(wvpResult);
  136. resultHolder.invokeAllResult(msg);
  137. return playResult;
  138. }
  139. String mediaServerId = streamInfo.getMediaServerId();
  140. MediaServerItem mediaInfo = mediaServerService.getOne(mediaServerId);
  141. JSONObject rtpInfo = zlmresTfulUtils.getRtpInfo(mediaInfo, streamId);
  142. if (rtpInfo.getInteger("code") == 0) {
  143. if (rtpInfo.getBoolean("exist")) {
  144. int localPort = rtpInfo.getInteger("local_port");
  145. if (localPort == 0) {
  146. logger.warn("[点播],点播时发现rtpServerC存在,但是尚未开始推流");
  147. // 此时说明rtpServer已经创建但是流还没有推上来
  148. WVPResult wvpResult = new WVPResult();
  149. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  150. wvpResult.setMsg("点播已经在进行中,请稍候重试");
  151. msg.setData(wvpResult);
  152. resultHolder.invokeAllResult(msg);
  153. return playResult;
  154. } else {
  155. WVPResult wvpResult = new WVPResult();
  156. wvpResult.setCode(ErrorCode.SUCCESS.getCode());
  157. wvpResult.setMsg(ErrorCode.SUCCESS.getMsg());
  158. wvpResult.setData(streamInfo);
  159. msg.setData(wvpResult);
  160. resultHolder.invokeAllResult(msg);
  161. if (hookEvent != null) {
  162. hookEvent.response(mediaServerItem, JSONObject.parseObject(JSON.toJSONString(streamInfo)));
  163. }
  164. }
  165. } else {
  166. redisCatchStorage.stopPlay(streamInfo);
  167. storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId());
  168. streamInfo = null;
  169. }
  170. } else {
  171. //zlm连接失败
  172. redisCatchStorage.stopPlay(streamInfo);
  173. storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId());
  174. streamInfo = null;
  175. }
  176. }
  177. if (streamInfo == null) {
  178. String streamId = null;
  179. if (mediaServerItem.isRtpEnable()) {
  180. streamId = String.format("%s_%s", device.getDeviceId(), channelId);
  181. }
  182. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, device.isSsrcCheck(), false);
  183. logger.info(JSONObject.toJSONString(ssrcInfo));
  184. play(mediaServerItem, ssrcInfo, device, channelId, (mediaServerItemInUse, response) -> {
  185. if (hookEvent != null) {
  186. hookEvent.response(mediaServerItem, response);
  187. }
  188. }, event -> {
  189. // sip error错误
  190. WVPResult wvpResult = new WVPResult();
  191. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  192. wvpResult.setMsg(String.format("点播失败, 错误码: %s, %s", event.statusCode, event.msg));
  193. msg.setData(wvpResult);
  194. resultHolder.invokeAllResult(msg);
  195. if (errorEvent != null) {
  196. errorEvent.response(event);
  197. }
  198. }, (code, msgStr) -> {
  199. // invite点播超时
  200. WVPResult wvpResult = new WVPResult();
  201. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  202. if (code == 0) {
  203. wvpResult.setMsg("点播超时,请稍候重试");
  204. } else if (code == 1) {
  205. wvpResult.setMsg("收流超时,请稍候重试");
  206. }
  207. msg.setData(wvpResult);
  208. // 回复之前所有的点播请求
  209. resultHolder.invokeAllResult(msg);
  210. }, uuid);
  211. }
  212. return playResult;
  213. }
  214. @Override
  215. public void play(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo, Device device, String channelId,
  216. ZlmHttpHookSubscribe.Event hookEvent, SipSubscribe.Event errorEvent,
  217. InviteTimeOutCallback timeoutCallback, String uuid) {
  218. String streamId = null;
  219. if (mediaServerItem.isRtpEnable()) {
  220. streamId = String.format("%s_%s", device.getDeviceId(), channelId);
  221. }
  222. if (ssrcInfo == null) {
  223. ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, device.isSsrcCheck(), false);
  224. }
  225. logger.info("[点播开始] deviceId: {}, channelId: {},收流端口: {}, 收流模式:{}, SSRC: {}, SSRC校验:{}", device.getDeviceId(), channelId, ssrcInfo.getPort(), device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
  226. // 超时处理
  227. String timeOutTaskKey = UUID.randomUUID().toString();
  228. SSRCInfo finalSsrcInfo = ssrcInfo;
  229. System.out.println("设置超时任务: " + timeOutTaskKey);
  230. dynamicTask.startDelay(timeOutTaskKey, () -> {
  231. logger.info("[点播超时] 收流超时 deviceId: {}, channelId: {},端口:{}, SSRC: {}", device.getDeviceId(), channelId, finalSsrcInfo.getPort(), finalSsrcInfo.getSsrc());
  232. timeoutCallback.run(1, "收流超时");
  233. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  234. try {
  235. cmder.streamByeCmd(device, channelId, finalSsrcInfo.getStream(), null);
  236. } catch (InvalidArgumentException | ParseException | SipException e) {
  237. logger.error("[点播超时], 发送BYE失败 {}", e.getMessage());
  238. } catch (SsrcTransactionNotFoundException e) {
  239. timeoutCallback.run(0, "点播超时");
  240. mediaServerService.releaseSsrc(mediaServerItem.getId(), finalSsrcInfo.getSsrc());
  241. mediaServerService.closeRTPServer(mediaServerItem, finalSsrcInfo.getStream());
  242. streamSession.remove(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  243. }
  244. }, userSetting.getPlayTimeout());
  245. final String ssrc = ssrcInfo.getSsrc();
  246. final String stream = ssrcInfo.getStream();
  247. //端口获取失败的ssrcInfo 没有必要发送点播指令
  248. if (ssrcInfo.getPort() <= 0) {
  249. logger.info("[点播端口分配异常],deviceId={},channelId={},ssrcInfo={}", device.getDeviceId(), channelId, ssrcInfo);
  250. return;
  251. }
  252. try {
  253. cmder.playStreamCmd(mediaServerItem, ssrcInfo, device, channelId, (MediaServerItem mediaServerItemInuse, JSONObject response) -> {
  254. logger.info("收到订阅消息: " + response.toJSONString());
  255. System.out.println("停止超时任务: " + timeOutTaskKey);
  256. dynamicTask.stop(timeOutTaskKey);
  257. // hook响应
  258. onPublishHandlerForPlay(mediaServerItemInuse, response, device.getDeviceId(), channelId, uuid);
  259. hookEvent.response(mediaServerItemInuse, response);
  260. logger.info("[点播成功] deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
  261. }, (event) -> {
  262. ResponseEvent responseEvent = (ResponseEvent) event.event;
  263. String contentString = new String(responseEvent.getResponse().getRawContent());
  264. // 获取ssrc
  265. int ssrcIndex = contentString.indexOf("y=");
  266. // 检查是否有y字段
  267. if (ssrcIndex >= 0) {
  268. //ssrc规定长度为10字节,不取余下长度以避免后续还有“f=”字段 TODO 后续对不规范的非10位ssrc兼容
  269. String ssrcInResponse = contentString.substring(ssrcIndex + 2, ssrcIndex + 12);
  270. // 查询到ssrc不一致且开启了ssrc校验则需要针对处理
  271. if (ssrc.equals(ssrcInResponse)) {
  272. return;
  273. }
  274. logger.info("[点播消息] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse);
  275. if (!mediaServerItem.isRtpEnable() || device.isSsrcCheck()) {
  276. logger.info("[点播消息] SSRC修正 {}->{}", ssrc, ssrcInResponse);
  277. if (!mediaServerItem.getSsrcConfig().checkSsrc(ssrcInResponse)) {
  278. // ssrc 不可用
  279. // 释放ssrc
  280. mediaServerService.releaseSsrc(mediaServerItem.getId(), finalSsrcInfo.getSsrc());
  281. streamSession.remove(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  282. event.msg = "下级自定义了ssrc,但是此ssrc不可用";
  283. event.statusCode = 400;
  284. errorEvent.response(event);
  285. return;
  286. }
  287. // 单端口模式streamId也有变化,需要重新设置监听
  288. if (!mediaServerItem.isRtpEnable()) {
  289. // 添加订阅
  290. HookSubscribeForStreamChange hookSubscribe = HookSubscribeFactory.on_stream_changed("rtp", stream, true, "rtsp", mediaServerItem.getId());
  291. subscribe.removeSubscribe(hookSubscribe);
  292. hookSubscribe.getContent().put("stream", String.format("%08x", Integer.parseInt(ssrcInResponse)).toUpperCase());
  293. subscribe.addSubscribe(hookSubscribe, (MediaServerItem mediaServerItemInUse, JSONObject response) -> {
  294. logger.info("[ZLM HOOK] ssrc修正后收到订阅消息: " + response.toJSONString());
  295. dynamicTask.stop(timeOutTaskKey);
  296. // hook响应
  297. onPublishHandlerForPlay(mediaServerItemInUse, response, device.getDeviceId(), channelId, uuid);
  298. hookEvent.response(mediaServerItemInUse, response);
  299. });
  300. }
  301. // 关闭rtp server
  302. mediaServerService.closeRTPServer(mediaServerItem, finalSsrcInfo.getStream());
  303. // 重新开启ssrc server
  304. mediaServerService.openRTPServer(mediaServerItem, finalSsrcInfo.getStream(), ssrcInResponse, device.isSsrcCheck(), false, finalSsrcInfo.getPort());
  305. }
  306. }
  307. }, (event) -> {
  308. dynamicTask.stop(timeOutTaskKey);
  309. mediaServerService.closeRTPServer(mediaServerItem, finalSsrcInfo.getStream());
  310. // 释放ssrc
  311. mediaServerService.releaseSsrc(mediaServerItem.getId(), finalSsrcInfo.getSsrc());
  312. streamSession.remove(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  313. errorEvent.response(event);
  314. });
  315. } catch (InvalidArgumentException | SipException | ParseException e) {
  316. logger.error("[命令发送失败] 点播消息: {}", e.getMessage());
  317. dynamicTask.stop(timeOutTaskKey);
  318. mediaServerService.closeRTPServer(mediaServerItem, finalSsrcInfo.getStream());
  319. // 释放ssrc
  320. mediaServerService.releaseSsrc(mediaServerItem.getId(), finalSsrcInfo.getSsrc());
  321. streamSession.remove(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  322. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(new CmdSendFailEvent(null));
  323. eventResult.msg = "命令发送失败";
  324. errorEvent.response(eventResult);
  325. }
  326. }
  327. @Override
  328. public void onPublishHandlerForPlay(MediaServerItem mediaServerItem, JSONObject response, String deviceId, String channelId, String uuid) {
  329. RequestMessage msg = new RequestMessage();
  330. if (uuid != null) {
  331. msg.setId(uuid);
  332. }
  333. msg.setKey(DeferredResultHolder.CALLBACK_CMD_PLAY + deviceId + channelId);
  334. StreamInfo streamInfo = onPublishHandler(mediaServerItem, response, deviceId, channelId);
  335. if (streamInfo != null) {
  336. DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
  337. if (deviceChannel != null) {
  338. deviceChannel.setStreamId(streamInfo.getStream());
  339. storager.startPlay(deviceId, channelId, streamInfo.getStream());
  340. }
  341. redisCatchStorage.startPlay(streamInfo);
  342. WVPResult wvpResult = new WVPResult();
  343. wvpResult.setCode(ErrorCode.SUCCESS.getCode());
  344. wvpResult.setMsg(ErrorCode.SUCCESS.getMsg());
  345. wvpResult.setData(streamInfo);
  346. msg.setData(wvpResult);
  347. resultHolder.invokeAllResult(msg);
  348. } else {
  349. logger.warn("设备预览API调用失败!");
  350. msg.setData(WVPResult.fail(ErrorCode.ERROR100.getCode(), "设备预览API调用失败!"));
  351. resultHolder.invokeAllResult(msg);
  352. }
  353. }
  354. @Override
  355. public MediaServerItem getNewMediaServerItem(Device device) {
  356. if (device == null) {
  357. return null;
  358. }
  359. String mediaServerId = device.getMediaServerId();
  360. MediaServerItem mediaServerItem;
  361. if (mediaServerId == null || "".equals(device.getMediaServerId()) || "auto".equals(device.getMediaServerId())) {
  362. mediaServerItem = mediaServerService.getMediaServerForMinimumLoad();
  363. } else {
  364. mediaServerItem = mediaServerService.getOne(mediaServerId);
  365. }
  366. if (mediaServerItem == null) {
  367. logger.warn("点播时未找到可使用的ZLM...");
  368. }
  369. return mediaServerItem;
  370. }
  371. @Override
  372. public DeferredResult<WVPResult<StreamInfo>> playBack(String deviceId, String channelId, String startTime,
  373. String endTime, InviteStreamCallback inviteStreamCallback,
  374. PlayBackCallback callback) {
  375. Device device = storager.queryVideoDevice(deviceId);
  376. if (device == null) {
  377. return null;
  378. }
  379. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  380. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, true, true);
  381. return playBack(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, inviteStreamCallback, callback);
  382. }
  383. @Override
  384. public DeferredResult<WVPResult<StreamInfo>> playBack(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo,
  385. String deviceId, String channelId, String startTime,
  386. String endTime, InviteStreamCallback infoCallBack,
  387. PlayBackCallback playBackCallback) {
  388. if (mediaServerItem == null || ssrcInfo == null) {
  389. return null;
  390. }
  391. String uuid = UUID.randomUUID().toString();
  392. String key = DeferredResultHolder.CALLBACK_CMD_PLAYBACK + deviceId + channelId;
  393. Device device = storager.queryVideoDevice(deviceId);
  394. if (device == null) {
  395. throw new ControllerException(ErrorCode.ERROR100.getCode(), "设备: " + deviceId + "不存在");
  396. }
  397. DeferredResult<WVPResult<StreamInfo>> result = new DeferredResult<>(30000L);
  398. resultHolder.put(DeferredResultHolder.CALLBACK_CMD_PLAYBACK + deviceId + channelId, uuid, result);
  399. RequestMessage requestMessage = new RequestMessage();
  400. requestMessage.setId(uuid);
  401. requestMessage.setKey(key);
  402. PlayBackResult<RequestMessage> playBackResult = new PlayBackResult<>();
  403. String playBackTimeOutTaskKey = UUID.randomUUID().toString();
  404. dynamicTask.startDelay(playBackTimeOutTaskKey, () -> {
  405. logger.warn(String.format("设备回放超时,deviceId:%s ,channelId:%s", deviceId, channelId));
  406. playBackResult.setCode(ErrorCode.ERROR100.getCode());
  407. playBackResult.setMsg("回放超时");
  408. playBackResult.setData(requestMessage);
  409. try {
  410. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
  411. } catch (InvalidArgumentException | ParseException | SipException e) {
  412. logger.error("[录像流]回放超时 发送BYE失败 {}", e.getMessage());
  413. } catch (SsrcTransactionNotFoundException e) {
  414. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  415. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  416. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  417. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  418. }
  419. // 回复之前所有的点播请求
  420. playBackCallback.call(playBackResult);
  421. result.setResult(WVPResult.fail(ErrorCode.ERROR100.getCode(), "回放超时"));
  422. resultHolder.exist(DeferredResultHolder.CALLBACK_CMD_PLAYBACK + deviceId + channelId, uuid);
  423. }, userSetting.getPlayTimeout());
  424. SipSubscribe.Event errorEvent = event -> {
  425. dynamicTask.stop(playBackTimeOutTaskKey);
  426. requestMessage.setData(WVPResult.fail(ErrorCode.ERROR100.getCode(), String.format("回放失败, 错误码: %s, %s", event.statusCode, event.msg)));
  427. playBackResult.setCode(ErrorCode.ERROR100.getCode());
  428. playBackResult.setMsg(String.format("回放失败, 错误码: %s, %s", event.statusCode, event.msg));
  429. playBackResult.setData(requestMessage);
  430. playBackResult.setEvent(event);
  431. playBackCallback.call(playBackResult);
  432. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  433. };
  434. InviteStreamCallback hookEvent = (InviteStreamInfo inviteStreamInfo) -> {
  435. logger.info("收到回放订阅消息: " + inviteStreamInfo.getResponse().toJSONString());
  436. dynamicTask.stop(playBackTimeOutTaskKey);
  437. StreamInfo streamInfo = onPublishHandler(inviteStreamInfo.getMediaServerItem(), inviteStreamInfo.getResponse(), deviceId, channelId);
  438. if (streamInfo == null) {
  439. logger.warn("设备回放API调用失败!");
  440. playBackResult.setCode(ErrorCode.ERROR100.getCode());
  441. playBackResult.setMsg("设备回放API调用失败!");
  442. playBackCallback.call(playBackResult);
  443. return;
  444. }
  445. redisCatchStorage.startPlayback(streamInfo, inviteStreamInfo.getCallId());
  446. WVPResult<StreamInfo> success = WVPResult.success(streamInfo);
  447. requestMessage.setData(success);
  448. playBackResult.setCode(ErrorCode.SUCCESS.getCode());
  449. playBackResult.setMsg(ErrorCode.SUCCESS.getMsg());
  450. playBackResult.setData(requestMessage);
  451. playBackResult.setMediaServerItem(inviteStreamInfo.getMediaServerItem());
  452. playBackResult.setResponse(inviteStreamInfo.getResponse());
  453. playBackCallback.call(playBackResult);
  454. };
  455. try {
  456. cmder.playbackStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, infoCallBack,
  457. hookEvent, eventResult -> {
  458. if (eventResult.type == SipSubscribe.EventResultType.response) {
  459. ResponseEvent responseEvent = (ResponseEvent) eventResult.event;
  460. String contentString = new String(responseEvent.getResponse().getRawContent());
  461. // 获取ssrc
  462. int ssrcIndex = contentString.indexOf("y=");
  463. // 检查是否有y字段
  464. if (ssrcIndex >= 0) {
  465. //ssrc规定长度为10字节,不取余下长度以避免后续还有“f=”字段 TODO 后续对不规范的非10位ssrc兼容
  466. String ssrcInResponse = contentString.substring(ssrcIndex + 2, ssrcIndex + 12);
  467. // 查询到ssrc不一致且开启了ssrc校验则需要针对处理
  468. if (ssrcInfo.getSsrc().equals(ssrcInResponse)) {
  469. return;
  470. }
  471. logger.info("[回放消息] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse);
  472. if (!mediaServerItem.isRtpEnable() || device.isSsrcCheck()) {
  473. logger.info("[回放消息] SSRC修正 {}->{}", ssrcInfo.getSsrc(), ssrcInResponse);
  474. if (!mediaServerItem.getSsrcConfig().checkSsrc(ssrcInResponse)) {
  475. // ssrc 不可用
  476. // 释放ssrc
  477. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  478. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  479. eventResult.msg = "下级自定义了ssrc,但是此ssrc不可用";
  480. eventResult.statusCode = 400;
  481. errorEvent.response(eventResult);
  482. return;
  483. }
  484. // 单端口模式streamId也有变化,需要重新设置监听
  485. if (!mediaServerItem.isRtpEnable()) {
  486. // 添加订阅
  487. HookSubscribeForStreamChange hookSubscribe = HookSubscribeFactory.on_stream_changed("rtp", ssrcInfo.getStream(), true, "rtsp", mediaServerItem.getId());
  488. subscribe.removeSubscribe(hookSubscribe);
  489. hookSubscribe.getContent().put("stream", String.format("%08x", Integer.parseInt(ssrcInResponse)).toUpperCase());
  490. subscribe.addSubscribe(hookSubscribe, (MediaServerItem mediaServerItemInUse, JSONObject response) -> {
  491. logger.info("[ZLM HOOK] ssrc修正后收到订阅消息: " + response.toJSONString());
  492. dynamicTask.stop(playBackTimeOutTaskKey);
  493. // hook响应
  494. onPublishHandlerForPlay(mediaServerItemInUse, response, device.getDeviceId(), channelId, uuid);
  495. hookEvent.call(new InviteStreamInfo(mediaServerItem, null, eventResult.callId, "rtp", ssrcInfo.getStream()));
  496. });
  497. }
  498. // 关闭rtp server
  499. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  500. // 重新开启ssrc server
  501. mediaServerService.openRTPServer(mediaServerItem, ssrcInfo.getStream(), ssrcInResponse, device.isSsrcCheck(), true, ssrcInfo.getPort());
  502. }
  503. }
  504. }
  505. }, errorEvent);
  506. } catch (InvalidArgumentException | SipException | ParseException e) {
  507. logger.error("[命令发送失败] 回放: {}", e.getMessage());
  508. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(new CmdSendFailEvent(null));
  509. eventResult.msg = "命令发送失败";
  510. errorEvent.response(eventResult);
  511. }
  512. return result;
  513. }
  514. @Override
  515. public DeferredResult<WVPResult<StreamInfo>> download(String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, InviteStreamCallback infoCallBack, PlayBackCallback hookCallBack) {
  516. Device device = storager.queryVideoDevice(deviceId);
  517. if (device == null) {
  518. return null;
  519. }
  520. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  521. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, true, true);
  522. return download(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, downloadSpeed, infoCallBack, hookCallBack);
  523. }
  524. @Override
  525. public DeferredResult<WVPResult<StreamInfo>> download(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo, String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, InviteStreamCallback infoCallBack, PlayBackCallback hookCallBack) {
  526. if (mediaServerItem == null || ssrcInfo == null) {
  527. return null;
  528. }
  529. String uuid = UUID.randomUUID().toString();
  530. String key = DeferredResultHolder.CALLBACK_CMD_DOWNLOAD + deviceId + channelId;
  531. DeferredResult<WVPResult<StreamInfo>> result = new DeferredResult<>(30000L);
  532. Device device = storager.queryVideoDevice(deviceId);
  533. if (device == null) {
  534. throw new ControllerException(ErrorCode.ERROR400.getCode(), "设备:" + deviceId + "不存在");
  535. }
  536. resultHolder.put(key, uuid, result);
  537. RequestMessage requestMessage = new RequestMessage();
  538. requestMessage.setId(uuid);
  539. requestMessage.setKey(key);
  540. WVPResult<StreamInfo> wvpResult = new WVPResult<>();
  541. requestMessage.setData(wvpResult);
  542. PlayBackResult<RequestMessage> downloadResult = new PlayBackResult<>();
  543. downloadResult.setData(requestMessage);
  544. String downLoadTimeOutTaskKey = UUID.randomUUID().toString();
  545. dynamicTask.startDelay(downLoadTimeOutTaskKey, () -> {
  546. logger.warn(String.format("录像下载请求超时,deviceId:%s ,channelId:%s", deviceId, channelId));
  547. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  548. wvpResult.setMsg("录像下载请求超时");
  549. downloadResult.setCode(ErrorCode.ERROR100.getCode());
  550. downloadResult.setMsg("录像下载请求超时");
  551. hookCallBack.call(downloadResult);
  552. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  553. try {
  554. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
  555. } catch (InvalidArgumentException | ParseException | SipException e) {
  556. logger.error("[录像流]录像下载请求超时, 发送BYE失败 {}", e.getMessage());
  557. } catch (SsrcTransactionNotFoundException e) {
  558. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  559. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  560. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  561. }
  562. // 回复之前所有的点播请求
  563. hookCallBack.call(downloadResult);
  564. }, userSetting.getPlayTimeout());
  565. SipSubscribe.Event errorEvent = event -> {
  566. dynamicTask.stop(downLoadTimeOutTaskKey);
  567. downloadResult.setCode(ErrorCode.ERROR100.getCode());
  568. downloadResult.setMsg(String.format("录像下载失败, 错误码: %s, %s", event.statusCode, event.msg));
  569. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  570. wvpResult.setMsg(String.format("录像下载失败, 错误码: %s, %s", event.statusCode, event.msg));
  571. downloadResult.setEvent(event);
  572. hookCallBack.call(downloadResult);
  573. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  574. };
  575. try {
  576. cmder.downloadStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, downloadSpeed, infoCallBack,
  577. inviteStreamInfo -> {
  578. logger.info("收到订阅消息: " + inviteStreamInfo.getResponse().toJSONString());
  579. dynamicTask.stop(downLoadTimeOutTaskKey);
  580. StreamInfo streamInfo = onPublishHandler(inviteStreamInfo.getMediaServerItem(), inviteStreamInfo.getResponse(), deviceId, channelId);
  581. streamInfo.setStartTime(startTime);
  582. streamInfo.setEndTime(endTime);
  583. redisCatchStorage.startDownload(streamInfo, inviteStreamInfo.getCallId());
  584. wvpResult.setCode(ErrorCode.SUCCESS.getCode());
  585. wvpResult.setMsg(ErrorCode.SUCCESS.getMsg());
  586. wvpResult.setData(streamInfo);
  587. downloadResult.setCode(ErrorCode.SUCCESS.getCode());
  588. downloadResult.setMsg(ErrorCode.SUCCESS.getMsg());
  589. downloadResult.setMediaServerItem(inviteStreamInfo.getMediaServerItem());
  590. downloadResult.setResponse(inviteStreamInfo.getResponse());
  591. hookCallBack.call(downloadResult);
  592. }, errorEvent);
  593. } catch (InvalidArgumentException | SipException | ParseException e) {
  594. logger.error("[命令发送失败] 录像下载: {}", e.getMessage());
  595. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(new CmdSendFailEvent(null));
  596. eventResult.msg = "命令发送失败";
  597. errorEvent.response(eventResult);
  598. }
  599. return result;
  600. }
  601. @Override
  602. public StreamInfo getDownLoadInfo(String deviceId, String channelId, String stream) {
  603. StreamInfo streamInfo = redisCatchStorage.queryDownload(deviceId, channelId, stream, null);
  604. if (streamInfo != null) {
  605. if (streamInfo.getProgress() == 1) {
  606. return streamInfo;
  607. }
  608. // 获取当前已下载时长
  609. String mediaServerId = streamInfo.getMediaServerId();
  610. MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  611. if (mediaServerItem == null) {
  612. logger.warn("查询录像信息时发现节点已离线");
  613. return null;
  614. }
  615. if (mediaServerItem.getRecordAssistPort() > 0) {
  616. JSONObject jsonObject = assistRESTfulUtils.fileDuration(mediaServerItem, streamInfo.getApp(), streamInfo.getStream(), null);
  617. if (jsonObject != null && jsonObject.getInteger("code") == 0) {
  618. long duration = jsonObject.getLong("data");
  619. if (duration == 0) {
  620. streamInfo.setProgress(0);
  621. } else {
  622. String startTime = streamInfo.getStartTime();
  623. String endTime = streamInfo.getEndTime();
  624. long start = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(startTime);
  625. long end = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(endTime);
  626. BigDecimal currentCount = new BigDecimal(duration / 1000);
  627. BigDecimal totalCount = new BigDecimal(end - start);
  628. BigDecimal divide = currentCount.divide(totalCount, 2, RoundingMode.HALF_UP);
  629. double process = divide.doubleValue();
  630. streamInfo.setProgress(process);
  631. }
  632. }
  633. }
  634. }
  635. return streamInfo;
  636. }
  637. @Override
  638. public void onPublishHandlerForDownload(InviteStreamInfo inviteStreamInfo, String deviceId, String channelId, String uuid) {
  639. RequestMessage msg = new RequestMessage();
  640. msg.setKey(DeferredResultHolder.CALLBACK_CMD_DOWNLOAD + deviceId + channelId);
  641. msg.setId(uuid);
  642. StreamInfo streamInfo = onPublishHandler(inviteStreamInfo.getMediaServerItem(), inviteStreamInfo.getResponse(), deviceId, channelId);
  643. if (streamInfo != null) {
  644. redisCatchStorage.startDownload(streamInfo, inviteStreamInfo.getCallId());
  645. msg.setData(JSON.toJSONString(streamInfo));
  646. resultHolder.invokeResult(msg);
  647. } else {
  648. logger.warn("设备预览API调用失败!");
  649. msg.setData(WVPResult.fail(ErrorCode.ERROR100.getCode(), "设备预览API调用失败!"));
  650. resultHolder.invokeResult(msg);
  651. }
  652. }
  653. public StreamInfo onPublishHandler(MediaServerItem mediaServerItem, JSONObject resonse, String deviceId, String channelId) {
  654. String streamId = resonse.getString("stream");
  655. JSONArray tracks = resonse.getJSONArray("tracks");
  656. StreamInfo streamInfo = mediaService.getStreamInfoByAppAndStream(mediaServerItem, "rtp", streamId, tracks, null);
  657. streamInfo.setDeviceID(deviceId);
  658. streamInfo.setChannelId(channelId);
  659. return streamInfo;
  660. }
  661. @Override
  662. public void zlmServerOffline(String mediaServerId) {
  663. // 处理正在向上推流的上级平台
  664. List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  665. if (sendRtpItems.size() > 0) {
  666. for (SendRtpItem sendRtpItem : sendRtpItems) {
  667. if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  668. ParentPlatform platform = storager.queryParentPlatByServerGBId(sendRtpItem.getPlatformId());
  669. try {
  670. sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  671. } catch (SipException | InvalidArgumentException | ParseException e) {
  672. logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
  673. }
  674. }
  675. }
  676. }
  677. // 处理正在观看的国标设备
  678. List<SsrcTransaction> allSsrc = streamSession.getAllSsrc();
  679. if (allSsrc.size() > 0) {
  680. for (SsrcTransaction ssrcTransaction : allSsrc) {
  681. if (ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  682. Device device = deviceService.queryDevice(ssrcTransaction.getDeviceId());
  683. if (device == null) {
  684. continue;
  685. }
  686. try {
  687. cmder.streamByeCmd(device, ssrcTransaction.getChannelId(),
  688. ssrcTransaction.getStream(), null);
  689. } catch (InvalidArgumentException | ParseException | SipException |
  690. SsrcTransactionNotFoundException e) {
  691. logger.error("[zlm离线]为正在使用此zlm的设备, 发送BYE失败 {}", e.getMessage());
  692. }
  693. }
  694. }
  695. }
  696. }
  697. @Override
  698. public void zlmServerOnline(String mediaServerId) {
  699. // TODO 查找之前的点播,流如果不存在则给下级发送bye
  700. // MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  701. // zlmresTfulUtils.getMediaList(mediaServerItem, (mediaList ->{
  702. // Integer code = mediaList.getInteger("code");
  703. // if (code == 0) {
  704. // JSONArray data = mediaList.getJSONArray("data");
  705. // if (data == null || data.size() == 0) {
  706. // zlmServerOffline(mediaServerId);
  707. // }else {
  708. // Map<String, JSONObject> mediaListMap = new HashMap<>();
  709. // for (int i = 0; i < data.size(); i++) {
  710. // JSONObject json = data.getJSONObject(i);
  711. // String app = json.getString("app");
  712. // if ("rtp".equals(app)) {
  713. // String stream = json.getString("stream");
  714. // if (mediaListMap.get(stream) != null) {
  715. // continue;
  716. // }
  717. // mediaListMap.put(stream, json);
  718. // // 处理正在观看的国标设备
  719. // List<SsrcTransaction> ssrcTransactions = streamSession.getSsrcTransactionForAll(null, null, null, stream);
  720. // if (ssrcTransactions.size() > 0) {
  721. // for (SsrcTransaction ssrcTransaction : ssrcTransactions) {
  722. // if(ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  723. // cmder.streamByeCmd(ssrcTransaction.getDeviceId(), ssrcTransaction.getChannelId(),
  724. // ssrcTransaction.getStream(), null);
  725. // }
  726. // }
  727. // }
  728. // }
  729. // }
  730. // if (mediaListMap.size() > 0 ) {
  731. // // 处理正在向上推流的上级平台
  732. // List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  733. // if (sendRtpItems.size() > 0) {
  734. // for (SendRtpItem sendRtpItem : sendRtpItems) {
  735. // if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  736. // if (mediaListMap.get(sendRtpItem.getStreamId()) == null) {
  737. // ParentPlatform platform = storager.queryPlatformByServerGBId(sendRtpItem.getPlatformId());
  738. // sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  739. // }
  740. // }
  741. // }
  742. // }
  743. // }
  744. // }
  745. // }
  746. // }));
  747. }
  748. @Override
  749. public void pauseRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
  750. String key = redisCatchStorage.queryPlaybackForKey(null, null, streamId, null);
  751. StreamInfo streamInfo = redisCatchStorage.queryPlayback(null, null, streamId, null);
  752. if (null == streamInfo) {
  753. logger.warn("streamId不存在!");
  754. throw new ServiceException("streamId不存在");
  755. }
  756. streamInfo.setPause(true);
  757. RedisUtil.set(key, streamInfo);
  758. MediaServerItem mediaServerItem = mediaServerService.getOne(streamInfo.getMediaServerId());
  759. if (null == mediaServerItem) {
  760. logger.warn("mediaServer 不存在!");
  761. throw new ServiceException("mediaServer不存在");
  762. }
  763. // zlm 暂停RTP超时检查
  764. JSONObject jsonObject = zlmresTfulUtils.pauseRtpCheck(mediaServerItem, streamId);
  765. if (jsonObject == null || jsonObject.getInteger("code") != 0) {
  766. throw new ServiceException("暂停RTP接收失败");
  767. }
  768. Device device = storager.queryVideoDevice(streamInfo.getDeviceID());
  769. cmder.playPauseCmd(device, streamInfo);
  770. }
  771. @Override
  772. public void resumeRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
  773. String key = redisCatchStorage.queryPlaybackForKey(null, null, streamId, null);
  774. StreamInfo streamInfo = redisCatchStorage.queryPlayback(null, null, streamId, null);
  775. if (null == streamInfo) {
  776. logger.warn("streamId不存在!");
  777. throw new ServiceException("streamId不存在");
  778. }
  779. streamInfo.setPause(false);
  780. RedisUtil.set(key, streamInfo);
  781. MediaServerItem mediaServerItem = mediaServerService.getOne(streamInfo.getMediaServerId());
  782. if (null == mediaServerItem) {
  783. logger.warn("mediaServer 不存在!");
  784. throw new ServiceException("mediaServer不存在");
  785. }
  786. // zlm 暂停RTP超时检查
  787. JSONObject jsonObject = zlmresTfulUtils.resumeRtpCheck(mediaServerItem, streamId);
  788. if (jsonObject == null || jsonObject.getInteger("code") != 0) {
  789. throw new ServiceException("继续RTP接收失败");
  790. }
  791. Device device = storager.queryVideoDevice(streamInfo.getDeviceID());
  792. cmder.playResumeCmd(device, streamInfo);
  793. }
  794. }