PlayServiceImpl.java 55 KB

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