PlayServiceImpl.java 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. package com.genersoft.iot.vmp.service.impl;
  2. import java.math.BigDecimal;
  3. import java.math.RoundingMode;
  4. import java.util.*;
  5. import javax.sip.ResponseEvent;
  6. import com.genersoft.iot.vmp.conf.exception.ControllerException;
  7. import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.beans.factory.annotation.Qualifier;
  12. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  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.dto.HookSubscribeFactory;
  35. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeForStreamChange;
  36. import com.genersoft.iot.vmp.utils.DateUtil;
  37. import com.genersoft.iot.vmp.media.zlm.AssistRESTfulUtils;
  38. import com.genersoft.iot.vmp.media.zlm.ZLMHttpHookSubscribe;
  39. import com.genersoft.iot.vmp.media.zlm.ZLMRESTfulUtils;
  40. import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem;
  41. import com.genersoft.iot.vmp.service.IMediaServerService;
  42. import com.genersoft.iot.vmp.service.IMediaService;
  43. import com.genersoft.iot.vmp.service.IPlayService;
  44. import com.genersoft.iot.vmp.service.bean.InviteTimeOutCallback;
  45. import com.genersoft.iot.vmp.service.bean.PlayBackCallback;
  46. import com.genersoft.iot.vmp.service.bean.PlayBackResult;
  47. import com.genersoft.iot.vmp.service.bean.SSRCInfo;
  48. import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
  49. import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
  50. import com.genersoft.iot.vmp.vmanager.bean.WVPResult;
  51. import com.genersoft.iot.vmp.vmanager.gb28181.play.bean.PlayResult;
  52. import gov.nist.javax.sip.stack.SIPDialog;
  53. @SuppressWarnings(value = {"rawtypes", "unchecked"})
  54. @Service
  55. public class PlayServiceImpl implements IPlayService {
  56. private final static Logger logger = LoggerFactory.getLogger(PlayServiceImpl.class);
  57. @Autowired
  58. private IVideoManagerStorage storager;
  59. @Autowired
  60. private SIPCommander cmder;
  61. @Autowired
  62. private SIPCommanderFroPlatform sipCommanderFroPlatform;
  63. @Autowired
  64. private IRedisCatchStorage redisCatchStorage;
  65. @Autowired
  66. private DeferredResultHolder resultHolder;
  67. @Autowired
  68. private ZLMRESTfulUtils zlmresTfulUtils;
  69. @Autowired
  70. private AssistRESTfulUtils assistRESTfulUtils;
  71. @Autowired
  72. private IMediaService mediaService;
  73. @Autowired
  74. private IMediaServerService mediaServerService;
  75. @Autowired
  76. private VideoStreamSessionManager streamSession;
  77. @Autowired
  78. private UserSetting userSetting;
  79. @Autowired
  80. private DynamicTask dynamicTask;
  81. @Autowired
  82. private ZLMHttpHookSubscribe subscribe;
  83. @Qualifier("taskExecutor")
  84. @Autowired
  85. private ThreadPoolTaskExecutor taskExecutor;
  86. @Override
  87. public PlayResult play(MediaServerItem mediaServerItem, String deviceId, String channelId,
  88. ZLMHttpHookSubscribe.Event hookEvent, SipSubscribe.Event errorEvent,
  89. Runnable timeoutCallback) {
  90. if (mediaServerItem == null) {
  91. throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到可用的zlm");
  92. }
  93. PlayResult playResult = new PlayResult();
  94. RequestMessage msg = new RequestMessage();
  95. String key = DeferredResultHolder.CALLBACK_CMD_PLAY + deviceId + channelId;
  96. msg.setKey(key);
  97. String uuid = UUID.randomUUID().toString();
  98. msg.setId(uuid);
  99. playResult.setUuid(uuid);
  100. DeferredResult<WVPResult<String>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
  101. playResult.setResult(result);
  102. // 录像查询以channelId作为deviceId查询
  103. resultHolder.put(key, uuid, result);
  104. Device device = redisCatchStorage.getDevice(deviceId);
  105. StreamInfo streamInfo = redisCatchStorage.queryPlayByDevice(deviceId, channelId);
  106. playResult.setDevice(device);
  107. result.onCompletion(()->{
  108. // 点播结束时调用截图接口
  109. taskExecutor.execute(()->{
  110. // TODO 应该在上流时调用更好,结束也可能是错误结束
  111. String path = "snap";
  112. String fileName = deviceId + "_" + channelId + ".jpg";
  113. WVPResult wvpResult = (WVPResult)result.getResult();
  114. if (Objects.requireNonNull(wvpResult).getCode() == 0) {
  115. StreamInfo streamInfoForSuccess = (StreamInfo)wvpResult.getData();
  116. MediaServerItem mediaInfo = mediaServerService.getOne(streamInfoForSuccess.getMediaServerId());
  117. String streamUrl = streamInfoForSuccess.getFmp4();
  118. // 请求截图
  119. logger.info("[请求截图]: " + fileName);
  120. zlmresTfulUtils.getSnap(mediaInfo, streamUrl, 15, 1, path, fileName);
  121. }
  122. });
  123. });
  124. if (streamInfo != null) {
  125. String streamId = streamInfo.getStream();
  126. if (streamId == null) {
  127. WVPResult wvpResult = new WVPResult();
  128. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  129. wvpResult.setMsg("点播失败, redis缓存streamId等于null");
  130. msg.setData(wvpResult);
  131. resultHolder.invokeAllResult(msg);
  132. return playResult;
  133. }
  134. String mediaServerId = streamInfo.getMediaServerId();
  135. MediaServerItem mediaInfo = mediaServerService.getOne(mediaServerId);
  136. JSONObject rtpInfo = zlmresTfulUtils.getRtpInfo(mediaInfo, streamId);
  137. if(rtpInfo.getInteger("code") == 0){
  138. if (rtpInfo.getBoolean("exist")) {
  139. WVPResult wvpResult = new WVPResult();
  140. wvpResult.setCode(ErrorCode.SUCCESS.getCode());
  141. wvpResult.setMsg(ErrorCode.SUCCESS.getMsg());
  142. wvpResult.setData(streamInfo);
  143. msg.setData(wvpResult);
  144. resultHolder.invokeAllResult(msg);
  145. if (hookEvent != null) {
  146. hookEvent.response(mediaServerItem, JSONObject.parseObject(JSON.toJSONString(streamInfo)));
  147. }
  148. }else {
  149. redisCatchStorage.stopPlay(streamInfo);
  150. storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId());
  151. streamInfo = null;
  152. }
  153. }else {
  154. //zlm连接失败
  155. redisCatchStorage.stopPlay(streamInfo);
  156. storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId());
  157. streamInfo = null;
  158. }
  159. }
  160. if (streamInfo == null) {
  161. String streamId = null;
  162. if (mediaServerItem.isRtpEnable()) {
  163. streamId = String.format("%s_%s", device.getDeviceId(), channelId);
  164. }
  165. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, device.isSsrcCheck(), false);
  166. logger.info(JSONObject.toJSONString(ssrcInfo));
  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(ErrorCode.ERROR100.getCode());
  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(ErrorCode.ERROR100.getCode());
  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. HookSubscribeForStreamChange hookSubscribe = HookSubscribeFactory.on_stream_changed("rtp", stream, true, "rtsp", mediaServerItem.getId());
  271. subscribe.removeSubscribe(hookSubscribe);
  272. hookSubscribe.getContent().put("stream", String.format("%08x", Integer.parseInt(ssrcInResponse)).toUpperCase());
  273. subscribe.addSubscribe(hookSubscribe, (MediaServerItem mediaServerItemInUse, JSONObject response)->{
  274. logger.info("[ZLM HOOK] ssrc修正后收到订阅消息: " + response.toJSONString());
  275. dynamicTask.stop(timeOutTaskKey);
  276. // hook响应
  277. onPublishHandlerForPlay(mediaServerItemInUse, response, device.getDeviceId(), channelId, uuid);
  278. hookEvent.response(mediaServerItemInUse, response);
  279. });
  280. }
  281. // 关闭rtp server
  282. mediaServerService.closeRTPServer(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  283. // 重新开启ssrc server
  284. mediaServerService.openRTPServer(mediaServerItem, finalSsrcInfo.getStream(), ssrcInResponse, device.isSsrcCheck(), false, finalSsrcInfo.getPort());
  285. }
  286. }
  287. }, (event) -> {
  288. dynamicTask.stop(timeOutTaskKey);
  289. mediaServerService.closeRTPServer(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  290. // 释放ssrc
  291. mediaServerService.releaseSsrc(mediaServerItem.getId(), finalSsrcInfo.getSsrc());
  292. streamSession.remove(device.getDeviceId(), channelId, finalSsrcInfo.getStream());
  293. errorEvent.response(event);
  294. });
  295. }
  296. @Override
  297. public void onPublishHandlerForPlay(MediaServerItem mediaServerItem, JSONObject response, String deviceId, String channelId, String uuid) {
  298. RequestMessage msg = new RequestMessage();
  299. if (uuid != null) {
  300. msg.setId(uuid);
  301. }
  302. msg.setKey(DeferredResultHolder.CALLBACK_CMD_PLAY + deviceId + channelId);
  303. StreamInfo streamInfo = onPublishHandler(mediaServerItem, response, deviceId, channelId);
  304. if (streamInfo != null) {
  305. DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
  306. if (deviceChannel != null) {
  307. deviceChannel.setStreamId(streamInfo.getStream());
  308. storager.startPlay(deviceId, channelId, streamInfo.getStream());
  309. }
  310. redisCatchStorage.startPlay(streamInfo);
  311. WVPResult wvpResult = new WVPResult();
  312. wvpResult.setCode(ErrorCode.SUCCESS.getCode());
  313. wvpResult.setMsg(ErrorCode.SUCCESS.getMsg());
  314. wvpResult.setData(streamInfo);
  315. msg.setData(wvpResult);
  316. resultHolder.invokeAllResult(msg);
  317. } else {
  318. logger.warn("设备预览API调用失败!");
  319. msg.setData(WVPResult.fail(ErrorCode.ERROR100.getCode(), "设备预览API调用失败!"));
  320. resultHolder.invokeAllResult(msg);
  321. }
  322. }
  323. @Override
  324. public MediaServerItem getNewMediaServerItem(Device device) {
  325. if (device == null) {
  326. return null;
  327. }
  328. String mediaServerId = device.getMediaServerId();
  329. MediaServerItem mediaServerItem;
  330. if (mediaServerId == null) {
  331. mediaServerItem = mediaServerService.getMediaServerForMinimumLoad();
  332. }else {
  333. mediaServerItem = mediaServerService.getOne(mediaServerId);
  334. }
  335. if (mediaServerItem == null) {
  336. logger.warn("点播时未找到可使用的ZLM...");
  337. }
  338. return mediaServerItem;
  339. }
  340. @Override
  341. public DeferredResult<WVPResult<StreamInfo>> playBack(String deviceId, String channelId, String startTime,
  342. String endTime,InviteStreamCallback inviteStreamCallback,
  343. PlayBackCallback callback) {
  344. Device device = storager.queryVideoDevice(deviceId);
  345. if (device == null) {
  346. return null;
  347. }
  348. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  349. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, true, true);
  350. return playBack(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, inviteStreamCallback, callback);
  351. }
  352. @Override
  353. public DeferredResult<WVPResult<StreamInfo>> playBack(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo,
  354. String deviceId, String channelId, String startTime,
  355. String endTime, InviteStreamCallback infoCallBack,
  356. PlayBackCallback playBackCallback) {
  357. if (mediaServerItem == null || ssrcInfo == null) {
  358. return null;
  359. }
  360. String uuid = UUID.randomUUID().toString();
  361. String key = DeferredResultHolder.CALLBACK_CMD_PLAYBACK + deviceId + channelId;
  362. Device device = storager.queryVideoDevice(deviceId);
  363. if (device == null) {
  364. throw new ControllerException(ErrorCode.ERROR100.getCode(), "设备: " + deviceId + "不存在");
  365. }
  366. DeferredResult<WVPResult<StreamInfo>> result = new DeferredResult<>(30000L);
  367. resultHolder.put(DeferredResultHolder.CALLBACK_CMD_PLAYBACK + deviceId + channelId, uuid, result);
  368. RequestMessage requestMessage = new RequestMessage();
  369. requestMessage.setId(uuid);
  370. requestMessage.setKey(key);
  371. PlayBackResult<RequestMessage> playBackResult = new PlayBackResult<>();
  372. String playBackTimeOutTaskKey = UUID.randomUUID().toString();
  373. dynamicTask.startDelay(playBackTimeOutTaskKey, ()->{
  374. logger.warn(String.format("设备回放超时,deviceId:%s ,channelId:%s", deviceId, channelId));
  375. playBackResult.setCode(ErrorCode.ERROR100.getCode());
  376. playBackResult.setMsg("回放超时");
  377. playBackResult.setData(requestMessage);
  378. SIPDialog dialog = streamSession.getDialogByStream(deviceId, channelId, ssrcInfo.getStream());
  379. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  380. if (dialog != null) {
  381. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  382. cmder.streamByeCmd(device.getDeviceId(), channelId, ssrcInfo.getStream(), null);
  383. }else {
  384. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  385. mediaServerService.closeRTPServer(deviceId, channelId, ssrcInfo.getStream());
  386. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  387. }
  388. cmder.streamByeCmd(device.getDeviceId(), channelId, ssrcInfo.getStream(), null);
  389. // 回复之前所有的点播请求
  390. playBackCallback.call(playBackResult);
  391. result.setResult(WVPResult.fail(ErrorCode.ERROR100.getCode(), "回放超时"));
  392. resultHolder.exist(DeferredResultHolder.CALLBACK_CMD_PLAYBACK + deviceId + channelId, uuid);
  393. }, userSetting.getPlayTimeout());
  394. cmder.playbackStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, infoCallBack,
  395. (InviteStreamInfo inviteStreamInfo) -> {
  396. logger.info("收到订阅消息: " + inviteStreamInfo.getResponse().toJSONString());
  397. dynamicTask.stop(playBackTimeOutTaskKey);
  398. StreamInfo streamInfo = onPublishHandler(inviteStreamInfo.getMediaServerItem(), inviteStreamInfo.getResponse(), deviceId, channelId);
  399. if (streamInfo == null) {
  400. logger.warn("设备回放API调用失败!");
  401. playBackResult.setCode(ErrorCode.ERROR100.getCode());
  402. playBackResult.setMsg("设备回放API调用失败!");
  403. playBackCallback.call(playBackResult);
  404. return;
  405. }
  406. redisCatchStorage.startPlayback(streamInfo, inviteStreamInfo.getCallId());
  407. WVPResult<StreamInfo> success = WVPResult.success(streamInfo);
  408. requestMessage.setData(success);
  409. playBackResult.setCode(ErrorCode.SUCCESS.getCode());
  410. playBackResult.setMsg(ErrorCode.SUCCESS.getMsg());
  411. playBackResult.setData(requestMessage);
  412. playBackResult.setMediaServerItem(inviteStreamInfo.getMediaServerItem());
  413. playBackResult.setResponse(inviteStreamInfo.getResponse());
  414. playBackCallback.call(playBackResult);
  415. }, event -> {
  416. dynamicTask.stop(playBackTimeOutTaskKey);
  417. requestMessage.setData(WVPResult.fail(ErrorCode.ERROR100.getCode(), String.format("回放失败, 错误码: %s, %s", event.statusCode, event.msg)));
  418. playBackResult.setCode(ErrorCode.ERROR100.getCode());
  419. playBackResult.setMsg(String.format("回放失败, 错误码: %s, %s", event.statusCode, event.msg));
  420. playBackResult.setData(requestMessage);
  421. playBackResult.setEvent(event);
  422. playBackCallback.call(playBackResult);
  423. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  424. });
  425. return result;
  426. }
  427. @Override
  428. public DeferredResult<WVPResult<StreamInfo>> download(String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, InviteStreamCallback infoCallBack, PlayBackCallback hookCallBack) {
  429. Device device = storager.queryVideoDevice(deviceId);
  430. if (device == null) {
  431. return null;
  432. }
  433. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  434. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, true, true);
  435. return download(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, downloadSpeed,infoCallBack, hookCallBack);
  436. }
  437. @Override
  438. public DeferredResult<WVPResult<StreamInfo>> download(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo, String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, InviteStreamCallback infoCallBack, PlayBackCallback hookCallBack) {
  439. if (mediaServerItem == null || ssrcInfo == null) {
  440. return null;
  441. }
  442. String uuid = UUID.randomUUID().toString();
  443. String key = DeferredResultHolder.CALLBACK_CMD_DOWNLOAD + deviceId + channelId;
  444. DeferredResult<WVPResult<StreamInfo>> result = new DeferredResult<>(30000L);
  445. Device device = storager.queryVideoDevice(deviceId);
  446. if (device == null) {
  447. throw new ControllerException(ErrorCode.ERROR400.getCode(), "设备:" + deviceId + "不存在");
  448. }
  449. resultHolder.put(key, uuid, result);
  450. RequestMessage requestMessage = new RequestMessage();
  451. requestMessage.setId(uuid);
  452. requestMessage.setKey(key);
  453. WVPResult<StreamInfo> wvpResult = new WVPResult<>();
  454. requestMessage.setData(wvpResult);
  455. PlayBackResult<RequestMessage> downloadResult = new PlayBackResult<>();
  456. downloadResult.setData(requestMessage);
  457. String downLoadTimeOutTaskKey = UUID.randomUUID().toString();
  458. dynamicTask.startDelay(downLoadTimeOutTaskKey, ()->{
  459. logger.warn(String.format("录像下载请求超时,deviceId:%s ,channelId:%s", deviceId, channelId));
  460. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  461. wvpResult.setMsg("录像下载请求超时");
  462. downloadResult.setCode(ErrorCode.ERROR100.getCode());
  463. downloadResult.setMsg("录像下载请求超时");
  464. hookCallBack.call(downloadResult);
  465. SIPDialog dialog = streamSession.getDialogByStream(deviceId, channelId, ssrcInfo.getStream());
  466. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  467. if (dialog != null) {
  468. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  469. cmder.streamByeCmd(device.getDeviceId(), channelId, ssrcInfo.getStream(), null);
  470. }else {
  471. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  472. mediaServerService.closeRTPServer(deviceId, channelId, ssrcInfo.getStream());
  473. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  474. }
  475. cmder.streamByeCmd(device.getDeviceId(), channelId, ssrcInfo.getStream(), null);
  476. // 回复之前所有的点播请求
  477. hookCallBack.call(downloadResult);
  478. }, userSetting.getPlayTimeout());
  479. cmder.downloadStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, downloadSpeed, infoCallBack,
  480. inviteStreamInfo -> {
  481. logger.info("收到订阅消息: " + inviteStreamInfo.getResponse().toJSONString());
  482. dynamicTask.stop(downLoadTimeOutTaskKey);
  483. StreamInfo streamInfo = onPublishHandler(inviteStreamInfo.getMediaServerItem(), inviteStreamInfo.getResponse(), deviceId, channelId);
  484. streamInfo.setStartTime(startTime);
  485. streamInfo.setEndTime(endTime);
  486. redisCatchStorage.startDownload(streamInfo, inviteStreamInfo.getCallId());
  487. wvpResult.setCode(ErrorCode.SUCCESS.getCode());
  488. wvpResult.setMsg(ErrorCode.SUCCESS.getMsg());
  489. wvpResult.setData(streamInfo);
  490. downloadResult.setCode(ErrorCode.SUCCESS.getCode());
  491. downloadResult.setMsg(ErrorCode.SUCCESS.getMsg());
  492. downloadResult.setMediaServerItem(inviteStreamInfo.getMediaServerItem());
  493. downloadResult.setResponse(inviteStreamInfo.getResponse());
  494. hookCallBack.call(downloadResult);
  495. }, event -> {
  496. dynamicTask.stop(downLoadTimeOutTaskKey);
  497. downloadResult.setCode(ErrorCode.ERROR100.getCode());
  498. downloadResult.setMsg(String.format("录像下载失败, 错误码: %s, %s", event.statusCode, event.msg));
  499. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  500. wvpResult.setMsg(String.format("录像下载失败, 错误码: %s, %s", event.statusCode, event.msg));
  501. downloadResult.setEvent(event);
  502. hookCallBack.call(downloadResult);
  503. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  504. });
  505. return result;
  506. }
  507. @Override
  508. public StreamInfo getDownLoadInfo(String deviceId, String channelId, String stream) {
  509. StreamInfo streamInfo = redisCatchStorage.queryDownload(deviceId, channelId, stream, null);
  510. if (streamInfo != null) {
  511. if (streamInfo.getProgress() == 1) {
  512. return streamInfo;
  513. }
  514. // 获取当前已下载时长
  515. String mediaServerId = streamInfo.getMediaServerId();
  516. MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  517. if (mediaServerItem == null) {
  518. logger.warn("查询录像信息时发现节点已离线");
  519. return null;
  520. }
  521. if (mediaServerItem.getRecordAssistPort() > 0) {
  522. JSONObject jsonObject = assistRESTfulUtils.fileDuration(mediaServerItem, streamInfo.getApp(), streamInfo.getStream(), null);
  523. if (jsonObject != null && jsonObject.getInteger("code") == 0) {
  524. long duration = jsonObject.getLong("data");
  525. if (duration == 0) {
  526. streamInfo.setProgress(0);
  527. }else {
  528. String startTime = streamInfo.getStartTime();
  529. String endTime = streamInfo.getEndTime();
  530. long start = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(startTime);
  531. long end = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(endTime);
  532. BigDecimal currentCount = new BigDecimal(duration/1000);
  533. BigDecimal totalCount = new BigDecimal(end-start);
  534. BigDecimal divide = currentCount.divide(totalCount,2, RoundingMode.HALF_UP);
  535. double process = divide.doubleValue();
  536. streamInfo.setProgress(process);
  537. }
  538. }
  539. }
  540. }
  541. return streamInfo;
  542. }
  543. @Override
  544. public void onPublishHandlerForDownload(InviteStreamInfo inviteStreamInfo, String deviceId, String channelId, String uuid) {
  545. RequestMessage msg = new RequestMessage();
  546. msg.setKey(DeferredResultHolder.CALLBACK_CMD_DOWNLOAD + deviceId + channelId);
  547. msg.setId(uuid);
  548. StreamInfo streamInfo = onPublishHandler(inviteStreamInfo.getMediaServerItem(), inviteStreamInfo.getResponse(), deviceId, channelId);
  549. if (streamInfo != null) {
  550. redisCatchStorage.startDownload(streamInfo, inviteStreamInfo.getCallId());
  551. msg.setData(JSON.toJSONString(streamInfo));
  552. resultHolder.invokeResult(msg);
  553. } else {
  554. logger.warn("设备预览API调用失败!");
  555. msg.setData(WVPResult.fail(ErrorCode.ERROR100.getCode(), "设备预览API调用失败!"));
  556. resultHolder.invokeResult(msg);
  557. }
  558. }
  559. public StreamInfo onPublishHandler(MediaServerItem mediaServerItem, JSONObject resonse, String deviceId, String channelId) {
  560. String streamId = resonse.getString("stream");
  561. JSONArray tracks = resonse.getJSONArray("tracks");
  562. StreamInfo streamInfo = mediaService.getStreamInfoByAppAndStream(mediaServerItem,"rtp", streamId, tracks, null);
  563. streamInfo.setDeviceID(deviceId);
  564. streamInfo.setChannelId(channelId);
  565. return streamInfo;
  566. }
  567. @Override
  568. public void zlmServerOffline(String mediaServerId) {
  569. // 处理正在向上推流的上级平台
  570. List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  571. if (sendRtpItems.size() > 0) {
  572. for (SendRtpItem sendRtpItem : sendRtpItems) {
  573. if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  574. ParentPlatform platform = storager.queryParentPlatByServerGBId(sendRtpItem.getPlatformId());
  575. sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  576. }
  577. }
  578. }
  579. // 处理正在观看的国标设备
  580. List<SsrcTransaction> allSsrc = streamSession.getAllSsrc();
  581. if (allSsrc.size() > 0) {
  582. for (SsrcTransaction ssrcTransaction : allSsrc) {
  583. if(ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  584. cmder.streamByeCmd(ssrcTransaction.getDeviceId(), ssrcTransaction.getChannelId(),
  585. ssrcTransaction.getStream(), null);
  586. }
  587. }
  588. }
  589. }
  590. @Override
  591. public void zlmServerOnline(String mediaServerId) {
  592. // TODO 查找之前的点播,流如果不存在则给下级发送bye
  593. // MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  594. // zlmresTfulUtils.getMediaList(mediaServerItem, (mediaList ->{
  595. // Integer code = mediaList.getInteger("code");
  596. // if (code == 0) {
  597. // JSONArray data = mediaList.getJSONArray("data");
  598. // if (data == null || data.size() == 0) {
  599. // zlmServerOffline(mediaServerId);
  600. // }else {
  601. // Map<String, JSONObject> mediaListMap = new HashMap<>();
  602. // for (int i = 0; i < data.size(); i++) {
  603. // JSONObject json = data.getJSONObject(i);
  604. // String app = json.getString("app");
  605. // if ("rtp".equals(app)) {
  606. // String stream = json.getString("stream");
  607. // if (mediaListMap.get(stream) != null) {
  608. // continue;
  609. // }
  610. // mediaListMap.put(stream, json);
  611. // // 处理正在观看的国标设备
  612. // List<SsrcTransaction> ssrcTransactions = streamSession.getSsrcTransactionForAll(null, null, null, stream);
  613. // if (ssrcTransactions.size() > 0) {
  614. // for (SsrcTransaction ssrcTransaction : ssrcTransactions) {
  615. // if(ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  616. // cmder.streamByeCmd(ssrcTransaction.getDeviceId(), ssrcTransaction.getChannelId(),
  617. // ssrcTransaction.getStream(), null);
  618. // }
  619. // }
  620. // }
  621. // }
  622. // }
  623. // if (mediaListMap.size() > 0 ) {
  624. // // 处理正在向上推流的上级平台
  625. // List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  626. // if (sendRtpItems.size() > 0) {
  627. // for (SendRtpItem sendRtpItem : sendRtpItems) {
  628. // if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  629. // if (mediaListMap.get(sendRtpItem.getStreamId()) == null) {
  630. // ParentPlatform platform = storager.queryPlatformByServerGBId(sendRtpItem.getPlatformId());
  631. // sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  632. // }
  633. // }
  634. // }
  635. // }
  636. // }
  637. // }
  638. // }
  639. // }));
  640. }
  641. }