PlayServiceImpl.java 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. package com.genersoft.iot.vmp.service.impl;
  2. import java.math.BigDecimal;
  3. import java.math.RoundingMode;
  4. import java.util.List;
  5. import java.util.Objects;
  6. import java.util.UUID;
  7. import javax.sip.ResponseEvent;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.http.HttpStatus;
  12. import org.springframework.http.ResponseEntity;
  13. import org.springframework.stereotype.Service;
  14. import org.springframework.web.context.request.async.DeferredResult;
  15. import com.alibaba.fastjson.JSON;
  16. import com.alibaba.fastjson.JSONArray;
  17. import com.alibaba.fastjson.JSONObject;
  18. import com.genersoft.iot.vmp.common.StreamInfo;
  19. import com.genersoft.iot.vmp.conf.DynamicTask;
  20. import com.genersoft.iot.vmp.conf.UserSetting;
  21. import com.genersoft.iot.vmp.gb28181.bean.Device;
  22. import com.genersoft.iot.vmp.gb28181.bean.DeviceChannel;
  23. import com.genersoft.iot.vmp.gb28181.bean.InviteStreamCallback;
  24. import com.genersoft.iot.vmp.gb28181.bean.InviteStreamInfo;
  25. import com.genersoft.iot.vmp.gb28181.bean.ParentPlatform;
  26. import com.genersoft.iot.vmp.gb28181.bean.SendRtpItem;
  27. import com.genersoft.iot.vmp.gb28181.bean.SsrcTransaction;
  28. import com.genersoft.iot.vmp.gb28181.event.SipSubscribe;
  29. import com.genersoft.iot.vmp.gb28181.session.VideoStreamSessionManager;
  30. import com.genersoft.iot.vmp.gb28181.transmit.callback.DeferredResultHolder;
  31. import com.genersoft.iot.vmp.gb28181.transmit.callback.RequestMessage;
  32. import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
  33. import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommanderFroPlatform;
  34. import com.genersoft.iot.vmp.media.zlm.AssistRESTfulUtils;
  35. import com.genersoft.iot.vmp.media.zlm.ZLMHttpHookSubscribe;
  36. import com.genersoft.iot.vmp.media.zlm.ZLMRESTfulUtils;
  37. import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem;
  38. import com.genersoft.iot.vmp.service.IMediaServerService;
  39. import com.genersoft.iot.vmp.service.IMediaService;
  40. import com.genersoft.iot.vmp.service.IPlayService;
  41. import com.genersoft.iot.vmp.service.bean.InviteTimeOutCallback;
  42. import com.genersoft.iot.vmp.service.bean.PlayBackCallback;
  43. import com.genersoft.iot.vmp.service.bean.PlayBackResult;
  44. import com.genersoft.iot.vmp.service.bean.SSRCInfo;
  45. import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
  46. import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
  47. import com.genersoft.iot.vmp.utils.DateUtil;
  48. import com.genersoft.iot.vmp.vmanager.bean.WVPResult;
  49. import com.genersoft.iot.vmp.vmanager.gb28181.play.bean.PlayResult;
  50. import gov.nist.javax.sip.stack.SIPDialog;
  51. @SuppressWarnings(value = {"rawtypes", "unchecked"})
  52. @Service
  53. public class PlayServiceImpl implements IPlayService {
  54. private final static Logger logger = LoggerFactory.getLogger(PlayServiceImpl.class);
  55. @Autowired
  56. private IVideoManagerStorage storager;
  57. @Autowired
  58. private SIPCommander cmder;
  59. @Autowired
  60. private SIPCommanderFroPlatform sipCommanderFroPlatform;
  61. @Autowired
  62. private IRedisCatchStorage redisCatchStorage;
  63. @Autowired
  64. private DeferredResultHolder resultHolder;
  65. @Autowired
  66. private ZLMRESTfulUtils zlmresTfulUtils;
  67. @Autowired
  68. private AssistRESTfulUtils assistRESTfulUtils;
  69. @Autowired
  70. private IMediaService mediaService;
  71. @Autowired
  72. private IMediaServerService mediaServerService;
  73. @Autowired
  74. private VideoStreamSessionManager streamSession;
  75. @Autowired
  76. private UserSetting userSetting;
  77. @Autowired
  78. private DynamicTask dynamicTask;
  79. @Autowired
  80. private ZLMHttpHookSubscribe subscribe;
  81. @Override
  82. public PlayResult play(MediaServerItem mediaServerItem, String deviceId, String channelId,
  83. ZLMHttpHookSubscribe.Event hookEvent, SipSubscribe.Event errorEvent,
  84. Runnable timeoutCallback) {
  85. PlayResult playResult = new PlayResult();
  86. RequestMessage msg = new RequestMessage();
  87. String key = DeferredResultHolder.CALLBACK_CMD_PLAY + deviceId + channelId;
  88. msg.setKey(key);
  89. String uuid = UUID.randomUUID().toString();
  90. msg.setId(uuid);
  91. playResult.setUuid(uuid);
  92. DeferredResult<ResponseEntity<String>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
  93. playResult.setResult(result);
  94. // 录像查询以channelId作为deviceId查询
  95. resultHolder.put(key, uuid, result);
  96. if (mediaServerItem == null) {
  97. WVPResult wvpResult = new WVPResult();
  98. wvpResult.setCode(-1);
  99. wvpResult.setMsg("未找到可用的zlm");
  100. msg.setData(wvpResult);
  101. resultHolder.invokeResult(msg);
  102. return playResult;
  103. }
  104. Device device = redisCatchStorage.getDevice(deviceId);
  105. StreamInfo streamInfo = redisCatchStorage.queryPlayByDevice(deviceId, channelId);
  106. playResult.setDevice(device);
  107. result.onCompletion(()->{
  108. // 点播结束时调用截图接口
  109. // TODO 应该在上流时调用更好,结束也可能是错误结束
  110. String path = "snap";
  111. String fileName = deviceId + "_" + channelId + ".jpg";
  112. ResponseEntity responseEntity = (ResponseEntity)result.getResult();
  113. if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
  114. WVPResult wvpResult = (WVPResult)responseEntity.getBody();
  115. if (Objects.requireNonNull(wvpResult).getCode() == 0) {
  116. StreamInfo streamInfoForSuccess = (StreamInfo)wvpResult.getData();
  117. MediaServerItem mediaInfo = mediaServerService.getOne(streamInfoForSuccess.getMediaServerId());
  118. String streamUrl = streamInfoForSuccess.getFmp4();
  119. // 请求截图
  120. logger.info("[请求截图]: " + fileName);
  121. zlmresTfulUtils.getSnap(mediaInfo, streamUrl, 15, 1, path, fileName);
  122. }
  123. }
  124. });
  125. if (streamInfo != null) {
  126. String streamId = streamInfo.getStream();
  127. if (streamId == null) {
  128. WVPResult wvpResult = new WVPResult();
  129. wvpResult.setCode(-1);
  130. wvpResult.setMsg("点播失败, redis缓存streamId等于null");
  131. msg.setData(wvpResult);
  132. resultHolder.invokeAllResult(msg);
  133. return playResult;
  134. }
  135. String mediaServerId = streamInfo.getMediaServerId();
  136. MediaServerItem mediaInfo = mediaServerService.getOne(mediaServerId);
  137. JSONObject rtpInfo = zlmresTfulUtils.getRtpInfo(mediaInfo, streamId);
  138. if(rtpInfo.getInteger("code") == 0){
  139. if (rtpInfo.getBoolean("exist")) {
  140. WVPResult wvpResult = new WVPResult();
  141. wvpResult.setCode(0);
  142. wvpResult.setMsg("success");
  143. wvpResult.setData(streamInfo);
  144. msg.setData(wvpResult);
  145. resultHolder.invokeAllResult(msg);
  146. if (hookEvent != null) {
  147. hookEvent.response(mediaServerItem, JSONObject.parseObject(JSON.toJSONString(streamInfo)));
  148. }
  149. }else {
  150. redisCatchStorage.stopPlay(streamInfo);
  151. storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId());
  152. streamInfo = null;
  153. }
  154. }else {
  155. //zlm连接失败
  156. redisCatchStorage.stopPlay(streamInfo);
  157. storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId());
  158. streamInfo = null;
  159. }
  160. }
  161. if (streamInfo == null) {
  162. String streamId = null;
  163. if (mediaServerItem.isRtpEnable()) {
  164. streamId = String.format("%s_%s", device.getDeviceId(), channelId);
  165. }
  166. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, device.isSsrcCheck(), false);
  167. play(mediaServerItem, ssrcInfo, device, channelId, (mediaServerItemInUse, response)->{
  168. if (hookEvent != null) {
  169. hookEvent.response(mediaServerItem, response);
  170. }
  171. }, event -> {
  172. // sip error错误
  173. WVPResult wvpResult = new WVPResult();
  174. wvpResult.setCode(-1);
  175. wvpResult.setMsg(String.format("点播失败, 错误码: %s, %s", event.statusCode, event.msg));
  176. msg.setData(wvpResult);
  177. resultHolder.invokeAllResult(msg);
  178. if (errorEvent != null) {
  179. errorEvent.response(event);
  180. }
  181. }, (code, msgStr)->{
  182. // invite点播超时
  183. WVPResult wvpResult = new WVPResult();
  184. wvpResult.setCode(-1);
  185. if (code == 0) {
  186. wvpResult.setMsg("点播超时,请稍候重试");
  187. }else if (code == 1) {
  188. wvpResult.setMsg("收流超时,请稍候重试");
  189. }
  190. msg.setData(wvpResult);
  191. // 回复之前所有的点播请求
  192. resultHolder.invokeAllResult(msg);
  193. }, uuid);
  194. }
  195. return playResult;
  196. }
  197. @Override
  198. public void play(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo, Device device, String channelId,
  199. ZLMHttpHookSubscribe.Event hookEvent, SipSubscribe.Event errorEvent,
  200. InviteTimeOutCallback timeoutCallback, String uuid) {
  201. String streamId = null;
  202. if (mediaServerItem.isRtpEnable()) {
  203. streamId = String.format("%s_%s", device.getDeviceId(), channelId);
  204. }
  205. if (ssrcInfo == null) {
  206. ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, device.isSsrcCheck(), false);
  207. }
  208. logger.info("[点播开始] deviceId: {}, channelId: {}, SSRC: {}", device.getDeviceId(), channelId, ssrcInfo.getSsrc() );
  209. // 超时处理
  210. String timeOutTaskKey = UUID.randomUUID().toString();
  211. SSRCInfo finalSsrcInfo = ssrcInfo;
  212. dynamicTask.startDelay( timeOutTaskKey,()->{
  213. SIPDialog dialog = streamSession.getDialogByStream(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  214. if (dialog != null) {
  215. logger.info("[点播超时] 收流超时 deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
  216. timeoutCallback.run(1, "收流超时");
  217. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  218. cmder.streamByeCmd(device.getDeviceId(), channelId, finalSsrcInfo.getStream(), null);
  219. }else {
  220. logger.info("[点播超时] 消息未响应 deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
  221. timeoutCallback.run(0, "点播超时");
  222. mediaServerService.releaseSsrc(mediaServerItem.getId(), finalSsrcInfo.getSsrc());
  223. mediaServerService.closeRTPServer(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  224. streamSession.remove(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  225. }
  226. }, userSetting.getPlayTimeout());
  227. final String ssrc = ssrcInfo.getSsrc();
  228. final String stream = ssrcInfo.getStream();
  229. //端口获取失败的ssrcInfo 没有必要发送点播指令
  230. if(ssrcInfo.getPort() <= 0){
  231. logger.info("[点播端口分配异常],deviceId={},channelId={},ssrcInfo={}", device.getDeviceId(), channelId, ssrcInfo);
  232. return;
  233. }
  234. cmder.playStreamCmd(mediaServerItem, ssrcInfo, device, channelId, (MediaServerItem mediaServerItemInuse, JSONObject response) -> {
  235. logger.info("收到订阅消息: " + response.toJSONString());
  236. dynamicTask.stop(timeOutTaskKey);
  237. // hook响应
  238. onPublishHandlerForPlay(mediaServerItemInuse, response, device.getDeviceId(), channelId, uuid);
  239. hookEvent.response(mediaServerItemInuse, response);
  240. logger.info("[点播成功] deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
  241. }, (event) -> {
  242. ResponseEvent responseEvent = (ResponseEvent)event.event;
  243. String contentString = new String(responseEvent.getResponse().getRawContent());
  244. // 获取ssrc
  245. int ssrcIndex = contentString.indexOf("y=");
  246. // 检查是否有y字段
  247. if (ssrcIndex >= 0) {
  248. //ssrc规定长度为10字节,不取余下长度以避免后续还有“f=”字段 TODO 后续对不规范的非10位ssrc兼容
  249. String ssrcInResponse = contentString.substring(ssrcIndex + 2, ssrcIndex + 12);
  250. // 查询到ssrc不一致且开启了ssrc校验则需要针对处理
  251. if (ssrc.equals(ssrcInResponse)) {
  252. return;
  253. }
  254. logger.info("[点播消息] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse );
  255. if (!mediaServerItem.isRtpEnable() || device.isSsrcCheck()) {
  256. logger.info("[SIP 消息] SSRC修正 {}->{}", ssrc, ssrcInResponse);
  257. if (!mediaServerItem.getSsrcConfig().checkSsrc(ssrcInResponse)) {
  258. // ssrc 不可用
  259. // 释放ssrc
  260. mediaServerService.releaseSsrc(mediaServerItem.getId(), finalSsrcInfo.getSsrc());
  261. streamSession.remove(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  262. event.msg = "下级自定义了ssrc,但是此ssrc不可用";
  263. event.statusCode = 400;
  264. errorEvent.response(event);
  265. return;
  266. }
  267. // 单端口模式streamId也有变化,需要重新设置监听
  268. if (!mediaServerItem.isRtpEnable()) {
  269. // 添加订阅
  270. JSONObject subscribeKey = new JSONObject();
  271. subscribeKey.put("app", "rtp");
  272. subscribeKey.put("stream", stream);
  273. subscribeKey.put("regist", true);
  274. subscribeKey.put("schema", "rtmp");
  275. subscribeKey.put("mediaServerId", mediaServerItem.getId());
  276. subscribe.removeSubscribe(ZLMHttpHookSubscribe.HookType.on_stream_changed,subscribeKey);
  277. subscribeKey.put("stream", String.format("%08x", Integer.parseInt(ssrcInResponse)).toUpperCase());
  278. subscribe.addSubscribe(ZLMHttpHookSubscribe.HookType.on_stream_changed, subscribeKey,
  279. (MediaServerItem mediaServerItemInUse, JSONObject response)->{
  280. logger.info("[ZLM HOOK] ssrc修正后收到订阅消息: " + response.toJSONString());
  281. dynamicTask.stop(timeOutTaskKey);
  282. // hook响应
  283. onPublishHandlerForPlay(mediaServerItemInUse, response, device.getDeviceId(), channelId, uuid);
  284. hookEvent.response(mediaServerItemInUse, response);
  285. });
  286. }
  287. // 关闭rtp server
  288. mediaServerService.closeRTPServer(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  289. // 重新开启ssrc server
  290. mediaServerService.openRTPServer(mediaServerItem, finalSsrcInfo.getStream(), ssrcInResponse, device.isSsrcCheck(), false);
  291. }
  292. }
  293. }, (event) -> {
  294. dynamicTask.stop(timeOutTaskKey);
  295. mediaServerService.closeRTPServer(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  296. // 释放ssrc
  297. mediaServerService.releaseSsrc(mediaServerItem.getId(), finalSsrcInfo.getSsrc());
  298. streamSession.remove(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  299. errorEvent.response(event);
  300. });
  301. }
  302. @Override
  303. public void onPublishHandlerForPlay(MediaServerItem mediaServerItem, JSONObject response, String deviceId, String channelId, String uuid) {
  304. RequestMessage msg = new RequestMessage();
  305. if (uuid != null) {
  306. msg.setId(uuid);
  307. }
  308. msg.setKey(DeferredResultHolder.CALLBACK_CMD_PLAY + deviceId + channelId);
  309. StreamInfo streamInfo = onPublishHandler(mediaServerItem, response, deviceId, channelId);
  310. if (streamInfo != null) {
  311. DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
  312. if (deviceChannel != null) {
  313. deviceChannel.setStreamId(streamInfo.getStream());
  314. storager.startPlay(deviceId, channelId, streamInfo.getStream());
  315. }
  316. redisCatchStorage.startPlay(streamInfo);
  317. WVPResult wvpResult = new WVPResult();
  318. wvpResult.setCode(0);
  319. wvpResult.setMsg("success");
  320. wvpResult.setData(streamInfo);
  321. msg.setData(wvpResult);
  322. resultHolder.invokeAllResult(msg);
  323. } else {
  324. logger.warn("设备预览API调用失败!");
  325. msg.setData("设备预览API调用失败!");
  326. resultHolder.invokeAllResult(msg);
  327. }
  328. }
  329. @Override
  330. public MediaServerItem getNewMediaServerItem(Device device) {
  331. if (device == null) {
  332. return null;
  333. }
  334. String mediaServerId = device.getMediaServerId();
  335. MediaServerItem mediaServerItem;
  336. if (mediaServerId == null) {
  337. mediaServerItem = mediaServerService.getMediaServerForMinimumLoad();
  338. }else {
  339. mediaServerItem = mediaServerService.getOne(mediaServerId);
  340. }
  341. if (mediaServerItem == null) {
  342. logger.warn("点播时未找到可使用的ZLM...");
  343. }
  344. return mediaServerItem;
  345. }
  346. @Override
  347. public DeferredResult<ResponseEntity<String>> playBack(String deviceId, String channelId, String startTime,
  348. String endTime,InviteStreamCallback inviteStreamCallback,
  349. PlayBackCallback callback) {
  350. Device device = storager.queryVideoDevice(deviceId);
  351. if (device == null) {
  352. return null;
  353. }
  354. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  355. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, true, true);
  356. return playBack(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, inviteStreamCallback, callback);
  357. }
  358. @Override
  359. public DeferredResult<ResponseEntity<String>> playBack(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo,
  360. String deviceId, String channelId, String startTime,
  361. String endTime, InviteStreamCallback infoCallBack,
  362. PlayBackCallback playBackCallback) {
  363. if (mediaServerItem == null || ssrcInfo == null) {
  364. return null;
  365. }
  366. String uuid = UUID.randomUUID().toString();
  367. String key = DeferredResultHolder.CALLBACK_CMD_PLAYBACK + deviceId + channelId;
  368. DeferredResult<ResponseEntity<String>> result = new DeferredResult<>(30000L);
  369. Device device = storager.queryVideoDevice(deviceId);
  370. if (device == null) {
  371. result.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
  372. return result;
  373. }
  374. resultHolder.put(DeferredResultHolder.CALLBACK_CMD_PLAYBACK + deviceId + channelId, uuid, result);
  375. RequestMessage msg = new RequestMessage();
  376. msg.setId(uuid);
  377. msg.setKey(key);
  378. PlayBackResult<RequestMessage> playBackResult = new PlayBackResult<>();
  379. String playBackTimeOutTaskKey = UUID.randomUUID().toString();
  380. dynamicTask.startDelay(playBackTimeOutTaskKey, ()->{
  381. logger.warn(String.format("设备回放超时,deviceId:%s ,channelId:%s", deviceId, channelId));
  382. playBackResult.setCode(-1);
  383. playBackResult.setData(msg);
  384. playBackCallback.call(playBackResult);
  385. SIPDialog dialog = streamSession.getDialogByStream(deviceId, channelId, ssrcInfo.getStream());
  386. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  387. if (dialog != null) {
  388. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  389. cmder.streamByeCmd(device.getDeviceId(), channelId, ssrcInfo.getStream(), null);
  390. }else {
  391. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  392. mediaServerService.closeRTPServer(deviceId, channelId, ssrcInfo.getStream());
  393. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  394. }
  395. cmder.streamByeCmd(device.getDeviceId(), channelId, ssrcInfo.getStream(), null);
  396. // 回复之前所有的点播请求
  397. playBackCallback.call(playBackResult);
  398. }, userSetting.getPlayTimeout());
  399. cmder.playbackStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, infoCallBack,
  400. (InviteStreamInfo inviteStreamInfo) -> {
  401. logger.info("收到订阅消息: " + inviteStreamInfo.getResponse().toJSONString());
  402. dynamicTask.stop(playBackTimeOutTaskKey);
  403. StreamInfo streamInfo = onPublishHandler(inviteStreamInfo.getMediaServerItem(), inviteStreamInfo.getResponse(), deviceId, channelId);
  404. if (streamInfo == null) {
  405. logger.warn("设备回放API调用失败!");
  406. msg.setData("设备回放API调用失败!");
  407. playBackResult.setCode(-1);
  408. playBackResult.setData(msg);
  409. playBackCallback.call(playBackResult);
  410. return;
  411. }
  412. redisCatchStorage.startPlayback(streamInfo, inviteStreamInfo.getCallId());
  413. msg.setData(JSON.toJSONString(streamInfo));
  414. playBackResult.setCode(0);
  415. playBackResult.setData(msg);
  416. playBackResult.setMediaServerItem(inviteStreamInfo.getMediaServerItem());
  417. playBackResult.setResponse(inviteStreamInfo.getResponse());
  418. playBackCallback.call(playBackResult);
  419. }, event -> {
  420. dynamicTask.stop(playBackTimeOutTaskKey);
  421. msg.setData(String.format("回放失败, 错误码: %s, %s", event.statusCode, event.msg));
  422. playBackResult.setCode(-1);
  423. playBackResult.setData(msg);
  424. playBackResult.setEvent(event);
  425. playBackCallback.call(playBackResult);
  426. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  427. });
  428. return result;
  429. }
  430. @Override
  431. public DeferredResult<ResponseEntity<String>> download(String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, InviteStreamCallback infoCallBack, PlayBackCallback hookCallBack) {
  432. Device device = storager.queryVideoDevice(deviceId);
  433. if (device == null) {
  434. return null;
  435. }
  436. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  437. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, true, true);
  438. return download(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, downloadSpeed,infoCallBack, hookCallBack);
  439. }
  440. @Override
  441. public DeferredResult<ResponseEntity<String>> download(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo, String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, InviteStreamCallback infoCallBack, PlayBackCallback hookCallBack) {
  442. if (mediaServerItem == null || ssrcInfo == null) {
  443. return null;
  444. }
  445. String uuid = UUID.randomUUID().toString();
  446. String key = DeferredResultHolder.CALLBACK_CMD_DOWNLOAD + deviceId + channelId;
  447. DeferredResult<ResponseEntity<String>> result = new DeferredResult<>(30000L);
  448. Device device = storager.queryVideoDevice(deviceId);
  449. if (device == null) {
  450. result.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
  451. return result;
  452. }
  453. resultHolder.put(key, uuid, result);
  454. RequestMessage msg = new RequestMessage();
  455. msg.setId(uuid);
  456. msg.setKey(key);
  457. WVPResult<StreamInfo> wvpResult = new WVPResult<>();
  458. msg.setData(wvpResult);
  459. PlayBackResult<RequestMessage> downloadResult = new PlayBackResult<>();
  460. downloadResult.setData(msg);
  461. String downLoadTimeOutTaskKey = UUID.randomUUID().toString();
  462. dynamicTask.startDelay(downLoadTimeOutTaskKey, ()->{
  463. logger.warn(String.format("录像下载请求超时,deviceId:%s ,channelId:%s", deviceId, channelId));
  464. wvpResult.setCode(-1);
  465. wvpResult.setMsg("录像下载请求超时");
  466. downloadResult.setCode(-1);
  467. hookCallBack.call(downloadResult);
  468. SIPDialog dialog = streamSession.getDialogByStream(deviceId, channelId, ssrcInfo.getStream());
  469. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  470. if (dialog != null) {
  471. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  472. cmder.streamByeCmd(device.getDeviceId(), channelId, ssrcInfo.getStream(), null);
  473. }else {
  474. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  475. mediaServerService.closeRTPServer(deviceId, channelId, ssrcInfo.getStream());
  476. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  477. }
  478. cmder.streamByeCmd(device.getDeviceId(), channelId, ssrcInfo.getStream(), null);
  479. // 回复之前所有的点播请求
  480. hookCallBack.call(downloadResult);
  481. }, userSetting.getPlayTimeout());
  482. cmder.downloadStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, downloadSpeed, infoCallBack,
  483. inviteStreamInfo -> {
  484. logger.info("收到订阅消息: " + inviteStreamInfo.getResponse().toJSONString());
  485. dynamicTask.stop(downLoadTimeOutTaskKey);
  486. StreamInfo streamInfo = onPublishHandler(inviteStreamInfo.getMediaServerItem(), inviteStreamInfo.getResponse(), deviceId, channelId);
  487. streamInfo.setStartTime(startTime);
  488. streamInfo.setEndTime(endTime);
  489. redisCatchStorage.startDownload(streamInfo, inviteStreamInfo.getCallId());
  490. wvpResult.setCode(0);
  491. wvpResult.setMsg("success");
  492. wvpResult.setData(streamInfo);
  493. downloadResult.setCode(0);
  494. downloadResult.setMediaServerItem(inviteStreamInfo.getMediaServerItem());
  495. downloadResult.setResponse(inviteStreamInfo.getResponse());
  496. hookCallBack.call(downloadResult);
  497. }, event -> {
  498. dynamicTask.stop(downLoadTimeOutTaskKey);
  499. downloadResult.setCode(-1);
  500. wvpResult.setCode(-1);
  501. wvpResult.setMsg(String.format("录像下载失败, 错误码: %s, %s", event.statusCode, event.msg));
  502. downloadResult.setEvent(event);
  503. hookCallBack.call(downloadResult);
  504. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  505. });
  506. return result;
  507. }
  508. @Override
  509. public StreamInfo getDownLoadInfo(String deviceId, String channelId, String stream) {
  510. StreamInfo streamInfo = redisCatchStorage.queryDownload(deviceId, channelId, stream, null);
  511. if (streamInfo != null) {
  512. if (streamInfo.getProgress() == 1) {
  513. return streamInfo;
  514. }
  515. // 获取当前已下载时长
  516. String mediaServerId = streamInfo.getMediaServerId();
  517. MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  518. if (mediaServerItem == null) {
  519. logger.warn("查询录像信息时发现节点已离线");
  520. return null;
  521. }
  522. if (mediaServerItem.getRecordAssistPort() != 0) {
  523. JSONObject jsonObject = assistRESTfulUtils.fileDuration(mediaServerItem, streamInfo.getApp(), streamInfo.getStream(), null);
  524. if (jsonObject != null && jsonObject.getInteger("code") == 0) {
  525. long duration = jsonObject.getLong("data");
  526. if (duration == 0) {
  527. streamInfo.setProgress(0);
  528. }else {
  529. String startTime = streamInfo.getStartTime();
  530. String endTime = streamInfo.getEndTime();
  531. long start = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(startTime);
  532. long end = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(endTime);
  533. BigDecimal currentCount = new BigDecimal(duration/1000);
  534. BigDecimal totalCount = new BigDecimal(end-start);
  535. BigDecimal divide = currentCount.divide(totalCount,2, RoundingMode.HALF_UP);
  536. double process = divide.doubleValue();
  537. streamInfo.setProgress(process);
  538. }
  539. }
  540. }
  541. }
  542. return streamInfo;
  543. }
  544. @Override
  545. public void onPublishHandlerForDownload(InviteStreamInfo inviteStreamInfo, String deviceId, String channelId, String uuid) {
  546. RequestMessage msg = new RequestMessage();
  547. msg.setKey(DeferredResultHolder.CALLBACK_CMD_DOWNLOAD + deviceId + channelId);
  548. msg.setId(uuid);
  549. StreamInfo streamInfo = onPublishHandler(inviteStreamInfo.getMediaServerItem(), inviteStreamInfo.getResponse(), deviceId, channelId);
  550. if (streamInfo != null) {
  551. redisCatchStorage.startDownload(streamInfo, inviteStreamInfo.getCallId());
  552. msg.setData(JSON.toJSONString(streamInfo));
  553. resultHolder.invokeResult(msg);
  554. } else {
  555. logger.warn("设备预览API调用失败!");
  556. msg.setData("设备预览API调用失败!");
  557. resultHolder.invokeResult(msg);
  558. }
  559. }
  560. public StreamInfo onPublishHandler(MediaServerItem mediaServerItem, JSONObject resonse, String deviceId, String channelId) {
  561. String streamId = resonse.getString("stream");
  562. JSONArray tracks = resonse.getJSONArray("tracks");
  563. StreamInfo streamInfo = mediaService.getStreamInfoByAppAndStream(mediaServerItem,"rtp", streamId, tracks, null);
  564. streamInfo.setDeviceID(deviceId);
  565. streamInfo.setChannelId(channelId);
  566. return streamInfo;
  567. }
  568. @Override
  569. public void zlmServerOffline(String mediaServerId) {
  570. // 处理正在向上推流的上级平台
  571. List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  572. if (sendRtpItems.size() > 0) {
  573. for (SendRtpItem sendRtpItem : sendRtpItems) {
  574. if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  575. ParentPlatform platform = storager.queryParentPlatByServerGBId(sendRtpItem.getPlatformId());
  576. sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  577. }
  578. }
  579. }
  580. // 处理正在观看的国标设备
  581. List<SsrcTransaction> allSsrc = streamSession.getAllSsrc();
  582. if (allSsrc.size() > 0) {
  583. for (SsrcTransaction ssrcTransaction : allSsrc) {
  584. if(ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  585. cmder.streamByeCmd(ssrcTransaction.getDeviceId(), ssrcTransaction.getChannelId(),
  586. ssrcTransaction.getStream(), null);
  587. }
  588. }
  589. }
  590. }
  591. @Override
  592. public void zlmServerOnline(String mediaServerId) {
  593. // 似乎没啥需要做的
  594. }
  595. }