PlayServiceImpl.java 36 KB

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